Kobalt Lombok Configuration

Prerequisites

These are the pre-requisite of Project Lombok to configure in any applications and IDE.

Java >= 1.8
Gradle >= 4.x or Maven 3.6.x
Project Lombok >= 1.18.20

See Also:

Lombok Build Tool Configuration

To setup Lombok on any of the build tool required on time of compilation of code only. Lombok not required on time of testing, running or deployment of code. So while adding the lombok dependency always add as “provided”.

Kobalt Lombok Configuration

You can add lombok dependency as below for kobalt build tool

dependencies {
	provided("org.projectlombok:lombok:1.18.28")
}

References

Related Posts

Your Feedback Motivate Us

If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

Happy Learning !!!

STS (Spring Tool Suite) Lombok Configuration

In your STS based application, you can follow the below STS Lombok Configuration to support you IDE for Project Lombok annotations.

Prerequisites

These are the pre-requisite of Project Lombok to configure in any applications and IDE.

Java >= 1.8
Gradle >= 4.x or Maven 3.6.x
Project Lombok >= 1.18.20

Ways to configure Lombok in STS

In this post, you will know about the three ways on configuring the Lombok in you STS IDE.

  • Manually configure the STS
  • STS Plugin for Lombok
  • STS Software Center

Manually Configure STS for Lombok

  • Download the lombok.jar from https://projectlombok.org/download
  • Place this lombok.jar in you root folder of STS installation location
  • Double click on the jar, it will open open popup as below. Select the IDE location by click “Specify location”
  • Click on “install/update” button.
STS Lombok Configuration
STS Lombok Configuration 1
  • Click on “Install/Update” button. On successful installation you will get below screen
  • Click on “Quit Installer”
  • Restart you STS IDE to refresh the Lombok features in case already open.
STS Lombok Configuration
STS Lombok Configuration 2

Lombok STS Configuration by Plug-in

You can install lombok directly from within STS, and in that way, you can also include lombok as part of your team STS deployment configuration.

Follow below steps to configure the Lombok STS configuration by plug-in

  • Go to your STS “Help->Search->Install New Software” as given
STS Lombok Configuration by plug-in
STS Lombok Configuration by plug-in
STS Lombok Configuration by plug-in
STS Lombok Configuration by plug-in
  • Select the Lombok Plug-in check boxes and click on install button
  • After Installation successful, Restart your STS IDE to refresh lombok features.

STS Lombok from Software Center

Some of the latest version of STS IDE already supports Lombok Project. In this case you don’t required any of above steps:

To check Lombok Support in STS IDE you can follow these steps:

  • Go to the about dialogue
  • Supported version on Lombok detail will display at last in “Copy Write” section as given in screenshot.
STS Lombok Configuration
STS Lombok Configuration

References

Conclusion

In this post you have learned about the multiple ways of Lombok Project configuration in you STS IDE.

Related Posts

Your Feedback Motivate Us

If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

Happy Learning !!!

Eclipse Lombok Configuration

In your Eclipse based application, you can follow the below Eclipse Lombok Configuration to support you IDE for Project Lombok annotations.

Prerequisites

These are the pre-requisite of Project Lombok to configure in any applications and IDE.

Java >= 1.8
Gradle >= 4.x or Maven 3.6.x
Project Lombok >= 1.18.20

Ways to configure Lombok in Eclipse

In this post, you will know about the three ways on configuring the Lombok in you Eclipse IDE.

  • Manually configure the Eclipse
  • Eclipse Plugin for Lombok
  • Eclipse Software Center

Manually Configure Eclipse for Lombok

  • Download the lombok.jar from https://projectlombok.org/download
  • Place this lombok.jar in you root folder of eclipse installation location
  • Double click on the jar, it will open open popup as below. Select the IDE location by click “Specify location”
  • Click on “install/update” button.
Eclipse Lombok Configuration
Eclipse Lombok Configuration 1
  • Click on “Install/Update” button. On successful installation you will get below screen
  • Click on “Quit Installer”
  • Restart you eclipse IDE to refresh the Lombok features in case already open.
    Eclipse Lombok Configuration
    Eclipse Lombok Configuration 2

    Lombok Eclipse Configuration by Plug-in

    You can install lombok directly from within eclipse, and in that way, you can also include lombok as part of your team eclipse deployment configuration.

    Follow below steps to configure the Lombok Eclipse configuration by plug-in

    • Go to your eclipse “Help->Search->Install New Software” as given
    Eclipse Lombok Configuration by plug-in
    Eclipse Lombok Configuration by plug-in
    Eclipse Lombok Configuration by plug-in
    Eclipse Lombok Configuration by plug-in
    • Select the Lombok Plug-in check boxes and click on install button
    • After Installation successful, Restart your eclipse IDE to refresh lombok features.

    Eclipse Lombok from Software Center

    Some of the latest version of Eclipse IDE already supports Lombok Project. In this case you don’t required any of above steps:

    To check Lombok Support in eclipse IDE you can follow these steps:

    • Go to the about dialogue
    • Supported version on Lombok detail will display at last in “Copy Write” section as given in screenshot.
    Eclipse Lombok Configuration
    Eclipse Lombok Configuration

    References

    Conclusion

    In this post you have learned about the multiple ways of Lombok Project configuration in you eclipse IDE.

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    Ant Lombok Configuration

    In your Ant based application, you can follow the below Ant Lombok Configuration by adding the following Ant dependencies in your build.xml.

    Prerequisites

    These are the pre-requisite of Project Lombok to configure in any applications and IDE.

    Java >= 1.8
    Gradle >= 4.x or Maven 3.6.x
    Project Lombok >= 1.18.20
    
    See Also:

    Lombok Ant Dependency

    You can add below Lombok dependency in you build.xml

    <dependencies>
    	<dependency org="org.projectlombok" name="lombok" rev="1.18.28" conf="build->master" />
    </dependencies>
    

    Lombok Ant Add Jar

    you’ve to add lombok.jar in a lib dir, your javac task would have to look like below

    <javac srcdir="src" destdir="build" source="1.8">
    	<classpath location="lib/lombok.jar" />
    </javac>
    

    Note :you still have to download lombok.jar  and run it as a jar file, if you wish to program in eclipse. The plugin makes that part easier. Follow this link : Eclipse Lombok Configuration

    References

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    Gradle Lombok Configuration

    In your Gradle based application, you can follow the below Gradle Lombok Configuration by adding the following maven dependencies in your build.gradle.

    Prerequisites

    These are the pre-requisite of Project Lombok to configure in any applications and IDE.

    Java >= 1.8
    Gradle >= 4.x or Maven 3.6.x
    Project Lombok >= 1.18.20
    
    See Also:

    Lombok Gradle Dependency

    You can add below Lombok dependency in you build.gradle

    dependencies {
    	compileOnly 'org.projectlombok:lombok:1.18.20'
    	annotationProcessor 'org.projectlombok:lombok:1.18.20'
    	
    	testCompileOnly 'org.projectlombok:lombok:1.18.20'
    	testAnnotationProcessor 'org.projectlombok:lombok:1.18.20'
    }
    

    Now your application is all set for using the Lombok Annotations by adding above Gradle Lombok Configuration.

    Note :

    you still have to download lombok.jar (or find it in gradle’s caches) and run it as a jar file, if you wish to program in eclipse. The plugin makes that part easier. Follow this link : Eclipse Lombok Configuration

    References

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    Maven Lombok Configuration

    In your Maven based application, you can follow the below Maven Lombok Configuration by adding the following maven dependencies in your pom.xml.

    Prerequisites

    These are the pre-requisite of Project Lombok to configure in any applications and IDE.

    Java >= 1.8
    Gradle >= 4.x or Maven 3.6.x
    Project Lombok >= 1.18.20
    
    See Also:

    Lombok Maven Dependency

    You can add below Lombok dependency in you pom.xml

    <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.18.20</version>
          <scope>provided</scope>
    </dependency>
    

    Lombok Maven Compiler Plugin

    You can add below dependency in maven-compiler-plugin of your pom.xml

    <build>
          <plugins>      
                
                <plugin>
                      <groupId>org.apache.maven.plugins</groupId>
                      <artifactId>maven-compiler-plugin</artifactId>
                      <version>3.5.1</version>
                      <configuration>
                            <source>11</source> <!-- depending on your project -->
                            <target>11</target> <!-- depending on your project -->
                            <annotationProcessorPaths>
                                  <path>
                                        <groupId>org.projectlombok</groupId>
                                        <artifactId>lombok</artifactId>
                                        <version>1.18.20</version>
                                  </path>                              
                            </annotationProcessorPaths>
                      </configuration>
                </plugin>
    

    Now your application is all set for using the Lombok Annotations by adding above Maven Lombok Configuration.

    Note :

    you still have to download lombok.jar (or find it in Maven’s caches) and run it as a jar file, if you wish to program in eclipse. The plugin makes that part easier. Follow this link : Eclipse Lombok Configuration

    References

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    Project Lombok Tutorial

    In this Project Lombok tutorial, you will learn everything about the Lombok configuration, Lombok Annotations & Use Cases with examples. Lombok annotation will help a lot to you application development faster and clean code.

    Why Project Lombok?

    Java is broadly used object-oriented programming language. Java has major drawbacks of writing boilerplate code. To overcome this major drawback, save time and efforts of developers, Project Lombok comes into existence. When using any IDE to generate boilerplate code (getters/getters/constructor/toString()/hashCode() methods) or write is manually, it exist in source code that increase the lines of code, and reduce readability and maintainability of class. While using the Project Lombok annotations will reduce or remove all these boilerplate code.

    What is Project Lombok?

    As per Project Lombok

    “Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java. Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.”

    Project Lombok provides annotation-based Java library that allows you to minimize or remove boilerplate code of your application which saves time and effort of developers. Lombok offers various annotations for replacing Java code that is well known for being boilerplate, repetitive, or tedious to write. These annotation makes you Java classes clean for readability and maintainability.

    Example : Lombok annotation @Data on class level can take care of all you class getter/setter, toString() method, constructors (default, parametrize), equals() method and hashCode() method. so specifically no need to write or generate this code. Now from above example you can understand how useful is Project Lombok for save time, effort and maintainability of Java application.

    Features of Project Lombok

    Project Lombok Features

    How Project Lombok works?

    Lombok Project dependency will add to your application which will generate all the required code on compile based on annotations specify in class. So your class source code will be clean however your generated compiled class will have all the required methods as per annotations on class and field levels.

    How Project Lombok works

    How to configure Project Lombok?

    Build Tools Lombok Configuration

    IDE Lombok Configuration

    Project Lombok Packages


    The Project Lombok includes the following packages that are having many Lombok annotations and Java API for different purposes.

    • lombok
    • experimental
    • extern.apachecommons
    • extern.flogger
    • extern.java
    • extern.jbosslog
    • extern.log4j
    • extern.slf4j

    Project Lombok Classes

    ClassDescription
    ConfigurationKeysA container class containing all Lombok configuration keys that do not belong to a specific annotation.
    Project Lombok Classes

    Project Lombok Enums

    EnumDescription
    AccessLevelRepresents an AccessLevel.

    Lombok Annotations & Use Cases

    These are very useful Project Lombok annotations which can be use in any Java based applications. Click on Lombok annotations & Use cases to get example.

    Lombok Annotations & Use cases
    Lom Project Annotations
    AnnotationDescription
    @AllArgsConstructorGenerates an all-args constructor.
    @BuilderThe @Builder is class level annotation. @Builder creates a so-called ‘builder’ aspect to the class or the class that contains a member which is annotated with @Builder.
    @Builder.DefaultThe field annotated with @Default must have an initializing expression; that expression is taken as the default to be used if not explicitly set during building.
    @Builder.ObtainViaPut on a field (in case of @Builder on a type) or a parameter (for @Builder on a constructor or static method) to indicate how Lombok should obtain a value for this field or parameter given an instance; this is only relevant if toBuilder is true.
    @CleanupEnsures the variable declaration that you annotate will be cleaned up by calling its close method, regardless of what happens.
    @CustomLogCauses Lombok to generate a logger field based on a custom logger implementation.
    @DataGenerates getters for all fields, a useful toString method, and hashCode and equals implementations that check all non-transient fields.
    @EqualsAndHashCodeGenerates implementations for the equals and hashCode methods inherited by all objects, based on relevant fields.
    @EqualsAndHashCode.ExcludeIf present, do not include this field in the generated equals and hashCode methods.
    @EqualsAndHashCode.IncludeConfigure the behavior of how this member is treated in the equals and hashCode implementation; if on a method, include the method’s return value as part of calculating hashCode/equality.
    @GeneratedLombok will eventually automatically add this annotation to all generated constructors, methods, fields, and types.
    @GetterPut on any field to make Lombok build a standard getter.
    @NoArgsConstructorGenerates a no-args constructor.
    @NonNullIf put on a parameter, Lombok will insert a null-check at the start of the method /constructor’s body, throwing a NullPointerException with the parameter’s name as a message.
    @RequiredArgsConstructorGenerates a constructor with required arguments.
    @SetterPut on any field to make Lombok build a standard setter.
    @SingularThe singular annotation is used together with @Builder to create single element ‘add’ methods in the builder for collections.
    @SneakyThrows@SneakyThrow will avoid javac’s insistence that you either catch or throw onward any checked exceptions that statements in your method body declare they generate.
    @SynchronizedAlmost exactly like putting the ‘synchronized’ keyword on a method, except will synchronize on a private internal Object, so that other code not under your control doesn’t meddle with your thread management by locking on your own instance.
    @ToStringGenerates an implementation for the toString method inherited by all objects, consisting of printing the values of relevant fields.
    @ToString.ExcludeIf present, do not include this field in the generated toString.
    @ToString.IncludeConfigure the behavior of how this member is rendered in the toString; if on a method, include the method’s return value in the output.
    @valUse val as the type of any local variable declaration (even in a for-each statement), and the type will be inferred from the initializing expression.
    @ValueGenerates a lot of code that fits with a class that is a representation of an immutable entity.
    @varUse var as the type of any local variable declaration (even in a for statement), and the type will be inferred from the initializing expression (any further assignments to the variable are not involved in this type inference).
    @WithPut on any field to make Lombok build a ‘with’ – a withX method that produces a clone of this object (except for 1 field which gets a new value).
    Project Lombok Annotations & Use Cases

    References

    Conclusions

    In this Project Lombok Tutorial you have learned about everything about the Lombok annotations & uses cases with examples. Also learn about the dependencies configurations in applications and plugins configurations in different IDE.

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Solved] log4j2 dependency logs not showing

    Problem

    We have developed a maven based applications with Log4j2 and application are having multiple modules and dependencies added as jar in pom.xml. While running the application logs are generating for application only but log4j2 dependency logs are not showing for modules and dependent jars due to this causing problem in debugging or troubleshooting of application.

    Solution

    To resolve this log4j2 logs not displaying issue, the solution is to add Commons Logging Bridge dependency as below in your Maven pom.xml.

    <dependencies>
      ...
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-jcl</artifactId>
        <version>2.1.17</version>
      </dependency>
      ...
    </dependencies>
    

    As stated on the Apache Log4j web page:

    If existing components use Apache Commons Logging 1.x and you want to have this logging routed to Log4j 2, then add the above dependency but do not remove any Commons Logging 1.x dependencies.

    References

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Solved] AnnotationException: Unknown Id.generator

    Hibernate/JPA “AnnotationException: Unknown Id Generator” is very common exception for database based application development this exception occurred because of @SequenceGenerator for @ID not configured properly.

    Problem

    Running the following Hibernate’s/Spring Boot JPA annotation sequence generator with PostgreSQL/SQL Server database.

       @Id	
    	@Column(name="employee_id", nullable=false)	
    	@GeneratedValue(strategy = GenerationType.SEQUENCE ,generator="employee_id_seq")
    	private Integer employeeId;
    

    Throw the following Hibernate/JPA Unknown Id.generator exception.

    Caused by: org.hibernate.AnnotationException: Unknown Id.generator: employee_id_seq
    	at org.hibernate.cfg.BinderHelper.makeIdGenerator(BinderHelper.java:413)
    	at org.hibernate.cfg.AnnotationBinder.bindId(AnnotationBinder.java:1795)
    	at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1229)
    	at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:733)
    

    The sequence “employee_user_id_seq” is created in PostgreSQL/SQLServer database, what caused the above “AnnotationException: Unknown Id Generator”?

    Solution

    When declaring the ID generator startegy in Hibernate’s/JPA, use property with annotation @SequenceGenerator annotation strategy in entity class. Try the above case as following:

         @Id	
    	@Column(name="employee_id", nullable=false)	
    	@SequenceGenerator(name="my_seq", sequenceName="employee_id_seq")
    	@GeneratedValue(strategy = GenerationType.SEQUENCE ,generator="my_seq")
    	private Integer employeeId;
    

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Solved] No default constructor for entity

    This “InstantiationException: No default constructor for entity” is very common for all Hibernate or Spring Boot JPA application development. In this post you will learn about the problem and solutions to resolve it.

    Reason of InstantiationException “No default constructor for entity”

    The JPA specification requires that all persistent classes have a no-arg constructor. This constructor may be public or protected. Because the compiler automatically creates a default no-arg constructor when no other constructor is defined, only classes that define constructors must also include a no-arg constructor.

    In the next sections of post, you will learn about the more detail about the issue and solutions by different ways.

    Example

    import jakarta.persistence.Entity;
    import jakarta.persistence.GeneratedValue;
    import jakarta.persistence.GenerationType;
    import jakarta.persistence.Id;
    
    @Entity
    public class Employee {
    	@Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        private String name;
     
     
        //parameterize constructor
    	public Employee(String name) {
    		super();
    		this.name = name;
    	}
    	public Long getId() {
    		return id;
    	}
    	public void setId(Long id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	@Override
    	public String toString() {
    		return "Employee [id=" + id + ", name=" + name + "]";
    	}  
        
    }
    

    Stacktrace

    Caused by: org.springframework.orm.jpa.JpaSystemException: No default constructor for entity : com.facingissuesonit.model.Employee
    	at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:320) ~[spring-orm-6.0.11.jar:6.0.11]
    	at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:771) ~[spring-boot-3.1.2.jar:3.1.2]
    	... 8 common frames omitted
    Caused by: org.hibernate.InstantiationException: No default constructor for entity : com.facingissuesonit.model.Employee
    	at org.hibernate.metamodel.internal.EntityInstantiatorPojoStandard.instantiate(EntityInstantiatorPojoStandard.java:93) ~[hibernate-core-6.2.6.Final.jar:6.2.6.Final]
    	... 23 common frames omitted
    

    Problem

    The above Employee entity class is not having the default no-arg constructor, due to JPA specification it’s required and through above InstantionException or JPASystemException.

    Solutions

    There are many ways to resolve this issue:

    Solution 1: Add Default Constructor

    You can create Default Constructor as below with public or protected scope.,

    import jakarta.persistence.Entity;
    import jakarta.persistence.GeneratedValue;
    import jakarta.persistence.GenerationType;
    import jakarta.persistence.Id;
    
    @Entity
    public class Employee {
    	@Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        private String name;
        
        //Default Constructor
        public Employee() {
    	}
        //parameterize constructor
    	public Employee(String name) {
    		super();
    		this.name = name;
    	}
    	public Long getId() {
    		return id;
    	}
    	public void setId(Long id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	@Override
    	public String toString() {
    		return "Employee [id=" + id + ", name=" + name + "]";
    	}  
        
    }
    

    Solution 2: Lombok Annotations

    Lombok provide good annotations to reduce effort of development and clean code, once you use the annotation it’s automatically generate the code on compile classes. Specific to this issue you can use the above class as below with different annotations.

    See Also:

    @NoArgsConstructor

    When use @NoArgsConstructor the Lombok will generate default constructor of class on compile time. Ex:

    import jakarta.persistence.Entity;
    import jakarta.persistence.GeneratedValue;
    import jakarta.persistence.GenerationType;
    import jakarta.persistence.Id;
    @NoArgsConstructor
    @Entity
    public class Employee {
    	@Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        private String name;
        
        //Default Constructor automatically created by lombok
        //public Employee() {
    	//}
        //parameterize constructor
    	public Employee(String name) {
    		super();
    		this.name = name;
    	}
    	public Long getId() {
    		return id;
    	}
    	public void setId(Long id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	@Override
    	public String toString() {
    		return "Employee [id=" + id + ", name=" + name + "]";
    	}  
        
    }
    

    @Data

    Lombok @Data annotation more simplified and make your class for boiler plate code. Lombok annotation generate the code for required methods on compile time. Now you can see this class is more clean because no need to write code for getter & setter methods, default constructor, parameterize constructor , toString() method.

    import jakarta.persistence.Entity;
    import jakarta.persistence.GeneratedValue;
    import jakarta.persistence.GenerationType;
    import jakarta.persistence.Id;
    @Data
    @Entity
    public class Employee {
    	@Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        private String name;
        
     //all getter, setter methods, default constructors, parameterize constructor, toString() method for all above fields will create by lombok on compile class.
        
    }
    

    Conclusion

    In this post you have learned about the reason of “InstantiationException: No default constructor for entity” and different solutions to resolve this issue.

    References

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Solved] How to set HostName in Log Path for Log4j/Tomcat?

    This hostname requirement in Logs line or logs path required when logs collector like filebeat or logstash etc are sending the logs line to centralize logging location or all the servers are mounted with one drive where all logs are forwarding. if the logs path or logs line are having the host name then easily troubleshoot the issue by checking the hostname or server.

    Solutions

    Based on your requirement you can configure the HostName for logs, Here you will learn about the log4j/Log4j2 and tomcat logging configuration.

    Log4j/Log4j2 HostName Configuration

    Latest version of log4j/Log4j2 is having the property for HostName. You can print the host name as part of log line or also configure the log file name or folder path with host name.

    Configuration for log line:

    <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" 
    								value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m${hostname}%n" />
    

    Configuration for log file name:

    <param name="file" value="C:\\Users\\FacingIssuesOnIT\\App-${hostname}.log" />
    

    Configuration for log file folder path:

    <param name="file" value="C:\\Users\\FacingIssuesOnIT\\${hostname}\\App.log" />
    

    Complete Example

    Configure Host Name in Log4j/Log4j2

    Note: hostname property by default configured by log4j/log4j2, In case You can set any other property also you can set in your main method or application initializer as below:

    System.setProperty("HostName", InetAddress.getLocalHost().getHostName());
    

    Tomcat Logging Host Name Configuration

    Follow below step to configure host name in tomcat:

    • Add line of statement in your /conf/catalina.properties
    JAVA_OPTS="${JAVA_OPTS} -Dhostname=$HOSTNAME"
    

    Here the property -Dhostname will pass as additional parameter while run tomcat.

    • Update your conf/ logging.properties for replacing the statement

    from

    1catalina.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
    

    to

    1catalina.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/${hostname}/logs
    
    • In case want to print hostname as logs statement then update server.xml as below:
    <Valve className="org.apache.catalina.valves.AccessLogValue" directory="C:\FacingIssuesOnIT\${hostname}  prefix="localhost_access_log" suffix=".log" pattern="%h %l %u %t &quot; %r &quot; ${hostname} %s %b" />
    

    Conclusion

    In this post you learn about the hostname/IP printing in logs statement and configuring the path.

    References

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Solved] How to split large text/log file in windows? 

    This is very common problem in applications to generate big logs file because not properly configure the logging approach for log file size, indexing and archival some time these logs files in GB. When developer need to troubleshoot any issue then face problem to open these files in notepad or notepad++.

    The good approach ids to download this file in your local and split in equals logs size files.

    Solution

    There are many solution to split the log/text file but below solution help to all the developers with minimum effort.

    Follow step 3 in case you are already having git bash in your local

    1. If you don’t have Git/Git Bash, download at https://git-scm.com/download
    2. If you lost the shortcut to Git Bash, you can run it using C:\Program Files\Git\git-bash.exe
    3. Open the git bash where you place the big log/text file. Run the below commands as per your requirement.

    Split the file of 100 MB each

    split largeFile.txt -b 100m
    
    Split large log file in equal size each

    Here you can decide size as m for mega byte, b for byte with size. and use attribute -b for size.

    If you have noticed from screen shot all the logs files size is same.

    Split the file of 1000 line each

    split largeFile.txt -l 1000
    
    Split large log file in equal lines each

    Here attribute -l represent for number of lines.

    If you have noticed all the files size are different because depend on character in line.

    In the above examples the files are splitting by prefix as x and continuously increasing alphabets. Incase you want logical name with indexing follow below approach.

    Split the file with Suffix and Prefix

    In this approach you will learn about the logical file name as prefix and indexing.

    split myLargeFile.txt myLog_ -l 20000 -a 3 -d
    
    Split large log file in equal size with prefix and indexing

    In the above example myLog_ is prefix of generating file, -l is use for number of lines in each file, 3 -d is use for three digit indexing of file names.

    Conclusion

    In this this post you have learn about the problem of large log files and solution to split in equal size with different approaches.

    References

    https://stackoverflow.com/questions/31786287/how-to-split-large-text-file-in-windows

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    Spring Boot Features

    Spring Boot is so popular because of broadly use framework and also support almost all Java related technologies. It also help to develop scalable microservices with less configuration and fast deployments over the cloud. Spring boot can also be used for developing a broad variety of other type of applications:

    • Utilities
    • MVC Web applications
    • Reactive Web Applications
    • Serverless Applications
    • Asynchronous Applications
    • Mobile Backends
    • Microservices
    • And Many more

    See Also:

    Spring Boot Features

    Spring Boot having so many good features as follows which makes broadly use and popular.

    Dependency Management

    Spring Boot made dependency management easy by using the Spring Boot Starters which include all the required third party dependencies with compatible version of jars based on Spring Boot version.

    Ex: Most frequently use Spring Boot Starters are as follows (spring-boot-starter-web, spring-boot-starter-data-jpa, etc.)

    Suppose you need to work on Web application use the spring-boot-starter-web then all set for your web application development.

    Automatic Configuration

    Spring Boot auto configure the required properties with default values based on selected Spring Boot Starters. In case you need to want change default values you can override through application.properties or application.yaml.

    Ex:

    • Suppose , You have selected the spring-boot-starter-web the default tomcat start port is 8080, in case you want to change then override the property server.port=9080 in application.proprties now tomcat will start on port 9080.
    • Suppose , You have selected the spring-boot-starter-data-jpa the default database is H2 and driver will automatically configure with default properties. In case , you want to go with another database then add dependency in pom.xml and required properties in application.properties/ application.yaml.

    Note: You can also disabled the auto configuration of Spring Boot, refer post Spring Boot Auto Configuration.

    See :

    Built-in Web Server

    All the Spring Boot application comes with embedded tomcat server so that you can build application in form executable Uber jar with all dependencies and execute by just one click on jar.

    In case, you want to use the external HTTP/web server then exclude the default dependencies and configure the application WebInitializationContext.

    Microservice Development Made Easy

    You can package an application into a standalone uber .jar with a full Tomcat container embedded. This feature was borrowed from the Play framework’s application deployment model (though, Spring Boot can also create traditional .war files). This packaged approach of build in stand alone jar or war makes installing and deploying software much easier.

    Streamlined Testing

    Spring Boot speed up the Microservices Unit and Integration testing by configuring the spring-boot-starter-test and also provide the testing annotation as @SpringBootTest to simplified the test cases.

    No Code Generation

    Spring Boot makes developer life easy to reduce the boiler plate code and make dependency management and auto configuration by Spring Boot Starters. It also reduce the effort of writing queries, database connection handling etc.

    Ex: Use @Repository Annotation and create interface for Entity with extended JPARepository or CrudRepository . It will takes care of all required method no need to write any query.

    No XML Generation

    Spring Boot provide the Stereo Annotations which makes developer life easy for creating XML beans based configuration and handling scoped. Spring Boot take care of all these dependencies related things by simplified annotations.

    Ex: @SpringBootConfiguration, @Component, @ComponentScan, @Configuration, @ Repository etc.

    See Also:

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Solved] SQLServerException: The definition of object ‘XYZ’ has changed since it was compiled.

    JDBC/JPA throws this exception on runtime “com.microsoft.sqlserver.jdbc.SQLServerException: The definition of object ‘XYZ’ has changed since it was compiled.” when call the stored procedure from JAVA code. There can be multiple reason of this issue.

    Reason of Exception

    This issue occurred with SQL Server or DB objects because these pre-compiled and persist in DB. In your team member or other person opened any tool to modify the object, or opened the Object in any tool in editable mode then SQL Server maintain the state/versioning of changes but not save or executed. Now when your applications run then SQLServer is confused which version of SQL Object need to execute and throw this exception “SQLServerException: The definition of object ‘XYZ’ has changed since it was compiled“.

    • This issue can be occured by parameter sniffing also.
    • or Stored Procedure/ SQL Object opened in editable mode in any tool.

    Solutions:

    To solve this problem there are following ways:

    Solution 1: You can execute the stored procedure/SQL object with sp_recompile from JDBC Java code as below:

    call sp_recompile XYZ_SP
    

    Solution 2: You can alter the Stored Procedure as below syntax with WITH RECOMPILE

    Syntax:

    create procedure <proc_name>
    [<parameters]>
    WITH RECOMPILE
    AS 
    <codes>
    

    Solution 3: Recreate the stored procedure/ SQL Object with new name and change the reference of this SQL object new name on all the places.

    Recommendation

    The Solution 1 and Solution 2 both are having drawback as all the time before executing the stored procedure will re-compile the object. Solution 3 is good in case if you know all the references of uses of stored procedure/ SQL Object in your application/all applications.

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    Why Spring Boot?

    What is Spring Framework?

    Spring Framework is a popular, enterprise-level, open-source modular Java based framework for creating the production-grade, standalone applications that run over the JVM (java Virtual Machine).

    What is Spring Boot?

    Spring Boot tool is wrapper over the Spring Framework for faster and easier development of Web and Microservices based applications. It’s also provide the three additional capabilities

    • Autoconfiguration
    • An opinionated approach to configuration
    • The ability to create standalone applications
    • Embedded Servers (Tomcat. Jetty)
    • No XML configuration or @Configuration

    These Spring Boot features work together to provide you faster development with minimal fuss of configuration and boiler-plate code for application setup.

    According to IBM

    Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run

    Spring Boot dependency-starters allows plug-in/plug out of modules and auto-configuration reduces the lots of development and configuration efforts of developers. Spring Boot offers flexible XML configurations, database transactions, sturdy batch processing and relaxed administration, documentation and security for REST services and endpoints.

    How Spring Boot is use in Microservices?

    Microservice is an Architectural approach that allows the developers to build, organize and operate small independent services. Microservice provide a light weight model to run the each service for specific function that can support the business objective.

    Below are some advantages of Microservices with Spring Boot:

    • Minimum configuration
    • Time-saving (reduce production time)
    • Simple scalability
    • Easy deposition.

    See Also :

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Java] Diamond Pattern Java Program

    In this “Diamond Pattern” – We have written Java programs to print/draw Star (X) pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

    Logic

    In the Diamond Pattern following this logic,

    • Diamond will draw in two phases upper part and lower part (just opposite logic)
    • First and last row will have only one symbol.
    • Consider spaces from left before print symbols
    • Once last symbol print jump cursor to next row (n)
    Diamond Pattern

    This post covers following ways to print Diamond Pattern:

    Diamond Pattern Java Program: For Loop

    This Diamond Java Program is following the below for loop logic:

    package _1_patterns.diamond;
    
    import java.util.Scanner;
    
    public class DiamondPatterForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawDiamondPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawDiamondPattern(int n, char c) {
    
    		// prints upper section of the pattern
    		for (int i = 1; i <= n; i++) {
    			// print spaces from left
    			for (int j = n; j > i; j--) {
    				System.out.print(" ");
    			}
    			// print symbol in diamond
    			for (int j = 0; j < (i - 1) * 2; j++) {
    				System.out.print(c);
    			}
    			if (i == 0) {
    				// throws cursor to the next line as first row will have one symbol
    				System.out.print("\n");
    			} else {
    				// prints symbol and throws cursor to the next line
    				System.out.print(c + "\n");
    			}
    		}
    		// prints lower section of the pattern
    		for (int i = n - 1; i >= 1; i--) {
    			// print spaces from left
    			for (int j = n; j > i; j--) {
    				System.out.print(" ");
    			}
    			// print symbol of  diamond
    			for (int j = 0; j < (i - 1) * 2; j++) {
    				System.out.print(c);
    			}
    			if (i == 0) {
    				// throws cursor to the next line because last row will have one symbol
    				System.out.print("\n");
    			} else {
    				// prints symbol and throws cursor to the next line
    				System.out.print(c + "\n");
    			}
    		}
    	}
    }
    
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : X
           X
          XXX
         XXXXX
        XXXXXXX
       XXXXXXXXX
      XXXXXXXXXXX
     XXXXXXXXXXXXX
    XXXXXXXXXXXXXXX
     XXXXXXXXXXXXX
      XXXXXXXXXXX
       XXXXXXXXX
        XXXXXXX
         XXXXX
          XXX
           X

    Diamond Pattern Java Program: While Loop

    This Diamond Java Program is following the below while loop logic:

    package _1_patterns.diamond;
    
    import java.util.Scanner;
    
    public class DiamondPatterWhileLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawDiamondPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawDiamondPattern(int n, char c) {
    
    		// prints upper section of the pattern
    		int i = 0;
    		while (i <= n) {
    			// print spaces from left
    			int j = n;
    			while (j > i) {
    				System.out.print(" ");
    				j--;
    			}
    			// print symbol in diamond
    			j = 0;
    			while (j < (i - 1) * 2) {
    				System.out.print(c);
    				j++;
    			}
    			if (i == 0) {
    				// throws cursor to the next line as first row will have one symbol
    				System.out.print("\n");
    			} else {
    				// prints symbol and throws cursor to the next line
    				System.out.print(c + "\n");
    			}
    			i++;
    		}
    		// prints lower section of the pattern
    		i = n - 1;
    		while (i >= 1) {
    			// print spaces from left
    			int j = n;
    			while (j > i) {
    				System.out.print(" ");
    				j--;
    			}
    			// print symbol of diamond
    			j = 0;
    			while (j < (i - 1) * 2) {
    				System.out.print(c);
    				j++;
    			}
    			if (i == 0) {
    				// throws cursor to the next line because last row will have one symbol
    				System.out.print("\n");
    			} else {
    				// prints symbol and throws cursor to the next line
    				System.out.print(c + "\n");
    			}
    			i--;
    		}
    	}
    }
    
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : $
           $
          $$$
         $$$$$
        $$$$$$$
       $$$$$$$$$
      $$$$$$$$$$$
     $$$$$$$$$$$$$
    $$$$$$$$$$$$$$$
     $$$$$$$$$$$$$
      $$$$$$$$$$$
       $$$$$$$$$
        $$$$$$$
         $$$$$
          $$$
           $

    Diamond Pattern Java Program: Do-While Loop

    This Diamond Java Program is following the below do-while loop logic:

    package _1_patterns.diamond;
    
    import java.util.Scanner;
    
    public class DiamondPatterDoWhileLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawDiamondPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawDiamondPattern(int n, char c) {
    
    		// prints upper section of the pattern
    		int i = 0;
    		do {
    			// print spaces from left
    			int j = n;
    			do {
    				System.out.print(" ");
    				j--;
    			} while (j > i);
    			// print symbol in diamond
    			j = 0;
    			do {
    				System.out.print(c);
    				j++;
    			} while (j < (i - 1) * 2);
    			if (i == 0) {
    				// throws cursor to the next line as first row will have one symbol
    				System.out.print("\n");
    			} else {
    				// prints symbol and throws cursor to the next line
    				System.out.print(c + "\n");
    			}
    			i++;
    		} while (i <= n);
    		// prints lower section of the pattern
    		i = n - 1;
    		do {
    			// print spaces from left
    			int j = n;
    			do {
    				System.out.print(" ");
    				j--;
    			} while (j > i);
    			// print symbol of diamond
    			j = 0;
    			do {
    				System.out.print(c);
    				j++;
    			} while (j < (i - 1) * 2);
    			if (i == 0) {
    				// throws cursor to the next line because last row will have one symbol
    				System.out.print("\n");
    			} else {
    				// prints symbol and throws cursor to the next line
    				System.out.print(c + "\n");
    			}
    			i--;
    		} while (i >= 1);
    	}
    }
    
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : #
           #
          ###
         #####
        #######
       #########
      ###########
     #############
    ###############
     #############
      ###########
       #########
        #######
         #####
          ###
           #

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Java] Hollow Diamond Pattern Java Program

    In this “Hollow Diamond Pattern” – We have written Java programs to print/draw Star (X) pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

    Logic

    In the Hollow Diamond Pattern following this logic,

    • Hollow Diamond will draw in two phases upper part and lower part (just opposite logic)
    • First and last row will have only one symbol.
    • Consider spaces from left before print symbol and spaces before second symbol
    • Once last symbol print jump cursor to next row (\n)
    Hollow Diamond Pattern

    This post covers following ways to print Hollow Diamond Pattern:

    • Hollow Diamond Pattern Java Program: Using for Loop
    • Hollow Diamond Pattern Java Program: Using While Loop
    • Hollow Diamond Pattern Java Program : Using Do-While Loop

    Hollow Diamond Pattern Java Program: For Loop

    This Hollow Diamond Java Program is following the below for loop logic:

    package _1_patterns.hollow_diamond;
    
    import java.util.Scanner;
    
    public class HollowDiamondPatterForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawHollowDiamondPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawHollowDiamondPattern(int n, char c) {
    
    		// prints upper section of the pattern
    		for (int i = 1; i <= n; i++) {
    			// print spaces from left
    			for (int j = n; j > i; j--) {
    				System.out.print(" ");
    			}
    			// prints symbol
    			System.out.print(c);
    			// print spaces in diamond
    			for (int j = 1; j < (i - 1) * 2; j++) {
    				System.out.print(" ");
    			}
    			if (i == 1) {
    				// throws cursor to the next line as first row will have one symbol
    				System.out.print("\n");
    			} else {
    				// prints symbol and throws cursor to the next line
    				System.out.print(c + "\n");
    			}
    		}
    		// prints lower section of the pattern
    		for (int i = n - 1; i >= 1; i--) {
    			// print spaces from left
    			for (int j = n; j > i; j--) {
    				System.out.print(" ");
    			}
    			// prints symbol
    			System.out.print(c);
    			// print spaces of hollow diamond
    			for (int j = 1; j < (i - 1) * 2; j++) {
    				System.out.print(" ");
    			}
    			if (i == 1) {
    				// throws cursor to the next line because last row will have one symbol
    				System.out.print("\n");
    			} else {
    				// prints symbol and throws cursor to the next line
    				System.out.print(c + "\n");
    			}
    		}
    	}
    }
    
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : X
           X
          X X
         X   X
        X     X
       X       X
      X         X
     X           X
    X             X
     X           X
      X         X
       X       X
        X     X
         X   X
          X X
           X

    Hollow Diamond Pattern Java Program: While Loop

    This Hollow Diamond Java Program is following the below while loop logic:

    package _1_patterns.hollow_diamond;
    
    import java.util.Scanner;
    
    public class HollowDiamondPatterWhileLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawHollowDiamondPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawHollowDiamondPattern(int n, char c) {
    
    		// prints upper section of the pattern
    		int i = 1;
    		while (i <= n) {
    			// print spaces from left
    			int j = n;
    			while (j > i) {
    				System.out.print(" ");
    				j--;
    			}
    			// prints symbol
    			System.out.print(c);
    			// print spaces in diamond
    			j = 1;
    			while (j < (i - 1) * 2) {
    				System.out.print(" ");
    				j++;
    			}
    			if (i == 1) {
    				// throws cursor to the next line as first row will have one symbol
    				System.out.print("\n");
    			} else {
    				// prints symbol and throws cursor to the next line
    				System.out.print(c + "\n");
    			}
    			i++;
    		}
    		// prints lower section of the pattern
    		i = n - 1;
    		while (i >= 1) {
    			// print spaces from left
    			int j = n;
    			while (j > i) {
    				System.out.print(" ");
    				j--;
    			}
    			// prints symbol
    			System.out.print(c);
    			// print spaces of hollow diamond
    			j = 1;
    			while (j < (i - 1) * 2) {
    				System.out.print(" ");
    				j++;
    			}
    			if (i == 1) {
    				// throws cursor to the next line because last row will have one symbol
    				System.out.print("\n");
    			} else {
    				// prints symbol and throws cursor to the next line
    				System.out.print(c + "\n");
    			}
    			i--;
    		}
    	}
    }
    
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : &
           &
          & &
         &   &
        &     &
       &       &
      &         &
     &           &
    &             &
     &           &
      &         &
       &       &
        &     &
         &   &
          & &
           &
    

    Hollow Diamond Pattern Java Program: Do-While Loop

    This Hollow Diamond Java Program is following the below do-while loop logic:

    package _1_patterns.hollow_diamond;
    
    import java.util.Scanner;
    
    public class HollowDiamondPatterDoWhileLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawHollowDiamondPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawHollowDiamondPattern(int n, char c) {
    
    		// prints upper section of the pattern
    		int i = 1;
    		do {
    			// print spaces from left
    			int j = n;
    			do {
    				System.out.print(" ");
    				j--;
    			} while (j > i);
    			// prints symbol
    			System.out.print(c);
    			// print spaces in diamond
    			j = 1;
    			do {
    				System.out.print(" ");
    				j++;
    			} while (j < (i - 1) * 2);
    			if (i == 1) {
    				// throws cursor to the next line as first row will have one symbol
    				System.out.print("\n");
    			} else {
    				// prints symbol and throws cursor to the next line
    				System.out.print(c + "\n");
    			}
    			i++;
    		} while (i <= n);
    		// prints lower section of the pattern
    		i = n - 1;
    		do {
    			// print spaces from left
    			int j = n;
    			do {
    				System.out.print(" ");
    				j--;
    			} while (j > i);
    			// prints symbol
    			System.out.print(c);
    			// print spaces of hollow diamond
    			j = 1;
    			do {
    				System.out.print(" ");
    				j++;
    			} while (j < (i - 1) * 2);
    			if (i == 1) {
    				// throws cursor to the next line because last row will have one symbol
    				System.out.print("\n");
    			} else {
    				// prints symbol and throws cursor to the next line
    				System.out.print(c + "\n");
    			}
    			i--;
    		} while (i >= 1);
    	}
    }
    
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : %
           %
          % %
         %   %
        %     %
       %       %
      %         %
     %           %
    %             %
     %           %
      %         %
       %       %
        %     %
         %   %
          % %
           %
    

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Java] Floyd’s Triangle Pattern Java Program

    In this “Floyd’s Triangle Pattern” – We have written Java programs to print/draw pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

    What is Floyd’s Triangle?

    Floyd’s triangle is a right arrangements of first natural numbers in triangle form with first natural numbers. All these natural numbers are left to right aligned triangle.

    Example: Suppose if no of rows to be displayed is 10 then the desired output should display 10 rows as:

    Floyd’s Triangle Java Program

    Algorithms

    • Initialization of in memory variable count=1.
    • Outer loop will execute based on inserted size
    • Inner loop will execute the times number of variable in outer loop
    • Print count value inside the inner loop and increase the count by 1 (count++)

    Time Complexity: O(n2) for given n

    Auxiliary Space: O(1)

    Implementation

    This post covers following ways to print Floyd’s Triangle Pattern:

    • Floyd’s Triangle Pattern Java Program: Using for Loop
    • Floyd’s Triangle Pattern Java Program: Using While Loop
    • Floyd’s Triangle Pattern Java Program : Using Do-While Loop

    Floyd’s Triangle Pattern Java Program: For Loop

    This Floyd’s Triangle Java Program is following the below logic in method:

    package _1_patterns.Floyd_Triangle;
    
    import java.util.Scanner;
    
    public class FloydTrianglePatternForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		drawFloydTrianglePattern(size);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawFloydTrianglePattern(int n) {
    		// Creating and initializing variable for
            // rows, columns and display value
            int count = 1;
            // Outer loop for rows
            for (int i = 1; i <= n; i++) {
                // Inner loop for columns
                for (int j = 1; j <= i; j++) {
                    // Printing value to be displayed
                    System.out.print(count + "  ");
                    // Incremeting value displayed
                    count++;
                }
                // Print elements of next row
                System.out.println();
            }
    	}
    }
    

    Output

    Enter Pattern Size : 
    13
    1  
    2  3  
    4  5  6  
    7  8  9  10  
    11  12  13  14  15  
    16  17  18  19  20  21  
    22  23  24  25  26  27  28  
    29  30  31  32  33  34  35  36  
    37  38  39  40  41  42  43  44  45  
    46  47  48  49  50  51  52  53  54  55  
    56  57  58  59  60  61  62  63  64  65  66  
    67  68  69  70  71  72  73  74  75  76  77  78  
    79  80  81  82  83  84  85  86  87  88  89  90  91  
    

    Floyd’s Triangle Pattern Java Program: While Loop

    This Floyd’s Triangle Java Program is following the below logic in method:

    package _1_patterns.Floyd_Triangle;
    
    import java.util.Scanner;
    
    public class FloydTrianglePatternWhileLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		drawFloydTrianglePattern(size);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawFloydTrianglePattern(int n) {
    			// Creating and initializing variable for
            // rows, columns and display value
            int i=1, count = 1;
     
            // Outer loop for rows
            while (i <= n) {
            	int j = 1;
                // Inner loop for columns
                while (j <= i) {
                    // Printing value to be displayed
                    System.out.print(count + "  ");
                    // Incremeting value displayed
                    count++;
                    j++;
                }
                // Print elements of next row
                System.out.println();
                i++;
            }
    	}
    }
    

    Output

    Enter Pattern Size : 
    10
    1  
    2  3  
    4  5  6  
    7  8  9  10  
    11  12  13  14  15  
    16  17  18  19  20  21  
    22  23  24  25  26  27  28  
    29  30  31  32  33  34  35  36  
    37  38  39  40  41  42  43  44  45  
    46  47  48  49  50  51  52  53  54  55  

    Floyd’s Triangle Pattern Java Program: Do-While Loop

    This Floyd’s Triangle Java Program is following the below logic in method:

    package _1_patterns.floyd_triangle;
    
    import java.util.Scanner;
    
    public class FloydTrianglePatternDoWhileLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    		drawFloydTrianglePattern(size);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawFloydTrianglePattern(int n) {
    		// Creating and initializing variable for
    		// rows, columns and display value
    		int i = 1, count = 1;
    
    		// Outer loop for rows
    		do {
    			int j = 1;
    			// Inner loop for columns
    			do {
    				// Printing value to be displayed
    				System.out.print(count + "  ");
    				// Incremeting value displayed
    				count++;
    				j++; // increase loop count
    			} while (j <= i);
    			// Print elements of next row
    			System.out.println();
    			i++; // increase loop count
    		} while (i <= n);
    	}
    }
    

    Output

    Enter Pattern Size : 
    7
    1  
    2  3  
    4  5  6  
    7  8  9  10  
    11  12  13  14  15  
    16  17  18  19  20  21  
    22  23  24  25  26  27  28 

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Java] Pyramid Pattern Java Program

    In this “Print Pyramid Pattern” – We have written Java programs to print/draw Pyramid pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

    Pyramid Pattern Example

    This post covers following ways to print Pyramid Pattern:

    • Print Pyramid Pattern Java Program: Using for Loop
    • Print Pyramid Pattern Java Program: Using While Loop
    • Print Pyramid Pattern Java Program: Using Do-While Loop

    Pyramid Pattern Java Program: For Loop

    This Pyramid Pattern Java Program is following the below logic:

    1. This program will have three for loop : 1 outer for loop and 2 inner for loop
    2. Outer for loop is for number of rows or size of Pyramid.
    3. First inner for loop is spacing from left
    4. Second inner for loop is for printing the symbols, just double of spacing.
    package _1_patterns.pyramid;
    
    import java.util.Scanner;
    
    public class PyramidPatternForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawPyramidPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawPyramidPattern(int n, char c) {
    	for (int i = 1; i <= n; i++) {
    			for (int j = 0; j < n - i; j++)
    			{
    				System.out.print(" ");
    			}
    			for (int j = 0; j < (i * 2) - 1; j++)
    			{
    				System.out.print(c);
    			}
    			System.out.println();
    		}	
    	}
    }
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : #
                            #
                         ###
                     #####
                 #######
             #########
          ###########
       #############
    ###############
    

    Pyramid Pattern Java Program: While Loop

    This Pyramid Pattern Java Program is following the below logic:

    1. This program will have three while loop : 1 outer while loop and 2 inner while loop
    2. Outer while loop is for number of rows or size of Pyramid.
    3. First inner while loop is spacing from left
    4. Second inner while loop is for printing the symbols, just double of spacing.
    package _1_patterns.pyramid;
    
    import java.util.Scanner;
    
    public class PyramidPatternForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawPyramidPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawPyramidPattern(int n, char c) {
    		int i = 1, j;
    		while (i <= n) {
    			j = 0;
    			while (j++ < n - i) {
    				System.out.print(" ");
    			}
    			j = 0;
    			while (j++ < (i * 2) - 1) {
    				System.out.print(c);
    			}
    			System.out.println();
    			i++;
    		}
    	}
    }
    

    Output

    Enter Pattern Size : 
    7
    Enter Symbol : ^
                 ^
               ^^^
             ^^^^^
           ^^^^^^^
         ^^^^^^^^^
       ^^^^^^^^^^^
    ^^^^^^^^^^^^^
    

    Pyramid Pattern Java Program: Do-While Loop

    This Pyramid Pattern Java Program is following the below logic:

    1. This program will have three do-while loop : 1 outer do-while loop and 2 inner do-while loop
    2. Outer do-while loop is for number of rows or size of pyramid.
    3. First inner do-while loop is spacing from left
    4. Second inner do-while loop is for printing the symbols, just double of spacing.
    package _1_patterns.pyramid;
    
    import java.util.Scanner;
    
    public class PyramidPatternForLoop {
    public static void main(String[] args) {
    
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter Pattern Size : ");
        int size = sc.nextInt();
    
        System.out.print("Enter Symbol : ");
        char symbol = sc.next().charAt(0);
    
        drawPyramidPattern(size, symbol);
    
        // Close Scanner
        sc.close();
    }
    
    private static void drawPyramidPattern(int n, char c) {
    int i = 1, j;
    		do {
    			j = 0;
    			do {
    				System.out.print(" ");
    			} while (j++ < (n - i - 1));
    			j = 0;
    			do {
    				System.out.print(c);
    			} while (j++ < i * 2 - 2);
    			System.out.println();
    		} while (++i < n);
    	}
    }
    

    Output

    Enter Pattern Size : 
    9
    Enter Symbol : %
                             %
                          %%%
                       %%%%%
                    %%%%%%%
                %%%%%%%%%
             %%%%%%%%%%%
          %%%%%%%%%%%%%
       %%%%%%%%%%%%%%%
    %%%%%%%%%%%%%%%%%
    
    

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Java] Inverted Right Triangle Pattern Program

    In this “Print Inverted Right Triangle Pattern” – We have written Java programs to print/draw Inverted Right Triangle pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

    Inverted Right Triangle Pattern Example

    This post covers following ways to print Inverted Right Triangle Pattern:

    • Print Inverted Right Triangle Java Program: Using for Loop
    • Print Inverted Right Triangle Java Program: Using While Loop
    • Print Inverted Right Triangle Java Program: Using Do-While Loop

    Inverted Right Triangle Pattern Java Program: For Loop

    This Inverted Right Triangle Java Program is following the below logic:

    • Run the outer for loop till entered size (int i = n; i > 0; i–) to print symbol. Where the n represent the size of triangle.
    • Every in inner for loop (int j = 0; j < i; j++) this size will get reduce by one do print symbol and continue till outer loop is not completed.
    package _1_patterns.Inverted_Right_Triangle;
    
    import java.util.Scanner;
    
    public class InvertedRightTrianglePatternForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawInvertedRightTrianglePattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawInvertedRightTrianglePattern(int n, char c) {
    		for (int i = n; i > 0; i--) {
    			for (int j = 0; j < i; j++) {
    				System.out.print(c);
    			}
    			System.out.println();
    		}
    	}
    }
    

    Output

    Enter Pattern Size : 
    5
    Enter Symbol : *
    *****
    ****
    ***
    **
    *
    

    Inverted Right Triangle Pattern Java Program: While Loop

    This Inverted Right Triangle Java Program is following the below logic:

    • Run the outer while loop till entered size (i > 0) to print symbol. Where the n represent the size of triangle.
    • Every in inner while loop (j++ < i) this size will get reduce by one do print symbol and continue till outer loop is not completed.
    package _1_patterns.Inverted_Right_Triangle;
    
    import java.util.Scanner;
    
    public class InvertedRightTrianglePatternForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawInvertedRightTrianglePattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawInvertedRightTrianglePattern(int n, char c) {
    		int i = n, j;
    		while (i > 0) {
    			j = 0;
    			while (j++ < i) {
    				System.out.print(c);
    			}
    			System.out.println();
    			i--;
    		}
    	}
    }
    

    Output

    Enter Pattern Size : 
    7
    Enter Symbol : #
    #######
    ######
    #####
    ####
    ###
    ##
    #

    Inverted Right Triangle Pattern Java Program: Do-While Loop

    This Inverted Right Triangle Java Program is following the below logic:

    • Run the outer do-while loop till entered size (–i > 0) to print symbol. Where the n represent the size of triangle.
    • Every in inner do-while loop (++j < i) this size will get reduce by one do print symbol and continue till outer loop is not completed.
    package _1_patterns.Inverted_Right_Triangle;
    
    import java.util.Scanner;
    
    public class InvertedRightTrianglePatternForLoop {
    public static void main(String[] args) {
    
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter Pattern Size : ");
        int size = sc.nextInt();
    
        System.out.print("Enter Symbol : ");
        char symbol = sc.next().charAt(0);
    
        drawInvertedRightTrianglePattern(size, symbol);
    
        // Close Scanner
        sc.close();
    }
    
    private static void drawInvertedRightTrianglePattern(int n, char c) {
    int i = n;
    		do {
    			int j = 0;
    			do {
    				System.out.print(c);
    			} while (++j < i);
    			System.out.println();
    		} while (--i > 0);
    }
    }
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : $
    $$$$$$$$
    $$$$$$$
    $$$$$$
    $$$$$
    $$$$
    $$$
    $$
    $

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Solved] Maven “class file has wrong version X, should be Y”

    The java.lang.UnsupportedClassVersionError is a sub-class of LinkageError and ClassFormatError. The JVM (Java Virtual Machine) throw this error when try to read a file but Major and Minor Java version are not supported.

    This Java Major and Minor class error occurred while running through IDE eclipse/STS or any because you JAVA_HOME or path or IDE Build Path is configured with different version of Java (JDK/JRE) however your code is compiled with different version of IDE. or Maven pom.xml is configured with different java version while running the program over different JDK/JRE which is not match with Major and Minor version supported.

    In further post you will get to know about the resolution steps.

    Example of Error Messages:

    • Java

    java.lang.LinkageError: XYZ has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 55.0

    • Springboot

    java.lang.UnsupportedClassVersionError: XYZ has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 55.0

    • Maven

    class file has wrong version 61.0, should be 55.0

    Java Major Version

    These are the Java Major Versions

    JavaMajor Version
    2064
    1963
    1862
    1761
    1660
    1559
    1458
    1357
    1256
    1155
    1054
    953
    852
    751
    650
    549
    1.448
    1.347
    1.246
    1.145
    1.0.245

    How to check Java Major Version?

    Yu can run the below command in your command prompt.

    javap -v <path to class file> | grep "major"
    

    Example

    $ javap -v build/classes/com/FacingIssuesOnIT/Book.class | grep “major”

    How to fix Java Major and Minor Version Issue?

    Follow these steps to resolve Java Major & Minor version issue:

    Step 1: Go to command prompt and check for Java version

    Step 2: In case your system is having more than one version of Java and you want to run your application or code with specific version, then go to Application-> Right click->Select Properties->Go to Build Path->Go to Library and remove the default Library from Class Path and Module Path.

    Step 3: Click on Add Library Button and Select JRE System Library, click on Next button. If your JRE on default then select or go to alternate JRE and select Java path as below by Browse button. Click on Apply and Close button and then Finish button

    Step 4: Now go to the left panel and select correct compiler version as below and click on apply button.

    Step 5: If your application is Maven based then you have to make additional changes in your pom.xml also

    Properties Section

    <properties>
    		<java.version>20</java.version>
    </properties>
    

    Plugins Section

       <plugins>    
               <plugin>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<configuration>
    					<source>20</source>
    					<target>20</target>
    				</configuration>
    			</plugin>
    		</plugins>
    

    Now save all your changes and run your application or program. It will work fine.

    Reference

    https://en.wikipedia.org/wiki/Java_class_file#General_layout

    Conclusions

    In this post you have learned about the Java Major and Minor version and also to check way of checking through command prompt. If you are facing such exceptions also provided way to resolve it.

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Solved] Java LinkageError : Compiled by a more recent version of the Java Runtime (class file version X), this version of the Java Runtime only recognizes class file versions up to Y

    The java.lang.UnsupportedClassVersionError is a sub-class of LinkageError and ClassFormatError. The JVM (Java Virtual Machine) throw this error when try to read a file but Major and Minor Java version are not supported.

    This Java Major and Minor class error occurred while running through IDE eclipse/STS or any because you JAVA_HOME or path or IDE Build Path is configured with different version of Java (JDK/JRE) however your code is compiled with different version of IDE. or Maven pom.xml is configured with different java version while running the program over different JDK/JRE which is not match with Major and Minor version supported.

    In further post you will get to know about the resolution steps.

    Example of Error Messages:

    • Java

    java.lang.LinkageError: XYZ has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 55.0

    • Springboot

    java.lang.UnsupportedClassVersionError: XYZ has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 55.0

    • Maven

    class file has wrong version 61.0, should be 55.0

    Java Major Version

    These are the Java Major Versions

    JavaMajor Version
    2064
    1963
    1862
    1761
    1660
    1559
    1458
    1357
    1256
    1155
    1054
    953
    852
    751
    650
    549
    1.448
    1.347
    1.246
    1.145
    1.0.245

    How to check Java Major Version?

    Yu can run the below command in your command prompt.

    javap -v <path to class file> | grep "major"
    

    Example

    $ javap -v build/classes/com/FacingIssuesOnIT/Book.class | grep “major”

    How to fix Java Major and Minor Version Issue?

    Follow these steps to resolve Java Major & Minor version issue:

    Step 1: Go to command prompt and check for Java version

    Step 2: In case your system is having more than one version of Java and you want to run your application or code with specific version, then go to Application-> Right click->Select Properties->Go to Build Path->Go to Library and remove the default Library from Class Path and Module Path.

    Step 3: Click on Add Library Button and Select JRE System Library, click on Next button. If your JRE on default then select or go to alternate JRE and select Java path as below by Browse button. Click on Apply and Close button and then Finish button

    Step 4: Now go to the left panel and select correct compiler version as below and click on apply button.

    Step 5: If your application is Maven based then you have to make additional changes in your pom.xml also

    Properties Section

    <properties>
    		<java.version>20</java.version>
    </properties>
    

    Plugins Section

       <plugins>    
               <plugin>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<configuration>
    					<source>20</source>
    					<target>20</target>
    				</configuration>
    			</plugin>
    		</plugins>
    

    Now save all your changes and run your application or program. It will work fine.

    Reference

    https://en.wikipedia.org/wiki/Java_class_file#General_layout

    Conclusions

    In this post you have learned about the Java Major and Minor version and also to check way of checking through command prompt. If you are facing such exceptions also provided way to resolve it.

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Solved] Java UnsupportedClassVersionError : Compiled by a more recent version of the Java Runtime (class file version X), this version of the Java Runtime only recognizes class file versions up to Y

    The java.lang.UnsupportedClassVersionError is a sub-class of LinkageError and ClassFormatError. The JVM (Java Virtual Machine) throw this error when try to read a file but Major and Minor Java version are not supported.

    This Java Major and Minor class error occurred while running through IDE eclipse/STS or any because you JAVA_HOME or path or IDE Build Path is configured with different version of Java (JDK/JRE) however your code is compiled with different version of IDE. or Maven pom.xml is configured with different java version while running the program over different JDK/JRE which is not match with Major and Minor version supported.

    In further post you will get to know about the resolution steps.

    Example of Error Messages:

    • Java

    java.lang.LinkageError: XYZ has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 55.0

    • Springboot

    java.lang.UnsupportedClassVersionError: XYZ has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 55.0

    • Maven

    class file has wrong version 61.0, should be 55.0

    Java Major Version

    These are the Java Major Versions

    JavaMajor Version
    2064
    1963
    1862
    1761
    1660
    1559
    1458
    1357
    1256
    1155
    1054
    953
    852
    751
    650
    549
    1.448
    1.347
    1.246
    1.145
    1.0.245

    How to check Java Major Version?

    Yu can run the below command in your command prompt.

    javap -v <path to class file> | grep "major"
    

    Example

    $ javap -v build/classes/com/FacingIssuesOnIT/Book.class | grep “major”

    How to fix Java Major and Minor Version Issue?

    Follow these steps to resolve Java Major & Minor version issue:

    Step 1: Go to command prompt and check for Java version

    Step 2: In case your system is having more than one version of Java and you want to run your application or code with specific version, then go to Application-> Right click->Select Properties->Go to Build Path->Go to Library and remove the default Library from Class Path and Module Path.

    Step 3: Click on Add Library Button and Select JRE System Library, click on Next button. If your JRE on default then select or go to alternate JRE and select Java path as below by Browse button. Click on Apply and Close button and then Finish button

    Step 4: Now go to the left panel and select correct compiler version as below and click on apply button.

    Step 5: If your application is Maven based then you have to make additional changes in your pom.xml also

    Properties Section

    <properties>
    		<java.version>20</java.version>
    </properties>
    

    Plugins Section

       <plugins>    
               <plugin>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<configuration>
    					<source>20</source>
    					<target>20</target>
    				</configuration>
    			</plugin>
    		</plugins>
    

    Now save all your changes and run your application or program. It will work fine.

    Reference

    https://en.wikipedia.org/wiki/Java_class_file#General_layout

    Conclusions

    In this post you have learned about the Java Major and Minor version and also to check way of checking through command prompt. If you are facing such exceptions also provided way to resolve it.

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    Magic Number (CAFEBABE) for Java Class Files

    Every Java Developer knows about it, Java Compiler compiles a java source code into bytecode and stores it into .class file which will then get executed by JVM. But do you know all class file in Java starts with Magic Number CAFEBABE hash code?

    Magic Number CAFEBABE in Java Class File

    What are Magic Numbers?

    In computer systems, file type can either be identified by extension ( e.g. .jpeg, .txt, .pdf) or some specific text i.e. Magic Number in the starting content of each file.

    Magic numbers are constant numbers or text value which is used to identify the file format. Detecting such constants in files is a simple and effective way of distinguishing between many file formats and can yield further run-time information. For Example,

    • PDF files start with “%PDF” (hex 25 50 44 46).
    • JPEG image files begin with FF D8 and end with FF D9

    Similarly, Java compiled class files (bytecode) start with Hexadecimal number CAFEBABE.

    Why Magic Number CAFEBABE is required to start each Class File?

    Well, the file has to start with some magic number or string (e.g. CAFEBABE) to make it easy to recognize as a valid class file and not something else.

    In other words, JVM will only read and executes .class files which starts with hex number CAFEBABE and it skips rest of the files. So, CAFEBABE is must as first line for getting your class file executed by any JVM. Anyway Java compiler will take care of it while converting to byte code.

    What is history to choose Magic Number CAFEBABE for Java?

    As per Alastair Mayer, there are two reasons.

    32-bit magic numbers (CA FE BA BE i.e. 1 byte for each pair) are easier to handle and more likely to be unique. The Java team wanted something with the Java-coffee metaphor, and since there’s no ‘J’ or ‘V’ in hexadecimal, settled for something with CAFE in it. “CAFE BABE” was sexier than something like “A FAB CAFE” or “CAFE FACE”, and definitely didn’t like the implications of “CAFE A FAD” (or worse, “A BAD CAFE”)

    However, James Gosling, the father of Java programming language, once explained it as follows:

    We used to go to lunch at a place called St Michael’s Alley. According to local legend, in the deep dark past, the Grateful Dead used to perform there before they made it big. It was a pretty funky place that was definitely a Grateful Dead Kinda Place. When Jerry died, they even put up a little Buddhist-esque shrine. When we used to go there, we referred to the place as Cafe Dead.

    Somewhere along the line it was noticed that this was a HEX number. I was re-vamping some file format code and needed a couple of magic numbers: one for the persistent object file, and one for classes. I used CAFEDEAD for the object file format, and in grepping for 4 character hex words that fit after CAFE (it seemed to be a good theme) I hit on BABE and decided to use it.

    At that time, it didn’t seem terribly important or destined to go anywhere but the trash-can of history. So CAFEBABE became the class file format, and CAFEDEAD was the persistent object format. But the persistent object facility went away, and along with it went the use of CAFEDEAD – it was eventually replaced by RMI.

    How to Open Class File In Hex Format?

    To open .class file directly in any text editor, it doesn’t open in readable format. You required editor which supports opening file in Hex format. You can use notepad++ for that purpose. However, you need to install HEX-Editor plugin. Here are the steps for the same :

    1) Download and install Notepad++ from here.

    2) After opening Notepad++, Go to Plugins -> Plugin Manager -> Show Plugin Manager

    Notepad ++ HexEditor Plugin

    3) Search and check HEX-Editor Plugin. Click Install Button.

    Notepad ++ HexEditor Plugin

    4) Restart Notepad++. Go to Plugins -> HEX-Editor -> View in HEX

    Notepad ++ HexEditor Plugin

    5) That’s it. Open your class file and you can see ca fe ba be in the first line of it.

    Notepad ++ HexEditor Plugin

    Reference

    https://en.wikipedia.org/wiki/Java_class_file#General_layout

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Solved] InvalidPathException: Illegal char at index XYZ

    The java.nio.file.InvalidPathException is a Runtime and Unchecked Exception which occured while running the program when file string path cannot be converted to Path. There can be multiple reason of throwing this exception as below:

    • String path contains invalid characters..
    • String path is invalid for other file system specific reasons (Ex: windows use (\) while linux use(/))

    Note: When this issue occured it shows the string path index also where this path is invalid.

    InvalidPathException is sub class of IllegalArgumentException

    public class InvalidPathException extends IllegalArgumentException
    

    Invalid Path Example

    On Windows-based platforms, invalid path characters might include ASCII/Unicode characters 1 through 31, as well as pipe (|),null (\0) tab(\t) or It may contain ‘?’ , or ‘:’ or * in the wrong place.

    InvalidPathException Example

    When you execute this program over the Windows OS machine will through InvalidPathException because In Windows the directory path always separated by double slash (\) however in this program the last directory separator is having single slash(\) file name (test.txt) this will make the special character as ‘\t’ which is consider as tab character.
    Due to this JVM will consider this string path as invalid and throw InvalidPathException.

    public class InvalidPathExceptionExample
    	{
    	public static void main(String[] args) {
    		try {
    			List<String> allLines = Files.readAllLines(Paths.get("C:\\Users\\facingissuesonit\\Desktop\\logs\test.txt"));
    
    			for (String line : allLines) {
    				if(!line.contains("SAFE"))
    				System.out.println(line);
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    	}
    	
    

    Output

    	Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <	> at index 60: C:\Users\facingissuesonit\Desktop\logging   est.txt
    	at sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
    	at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
    	at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
    	at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
    	at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)
    	at java.nio.file.Paths.get(Paths.java:84)
    	at InvalidPathExceptionExample.main(ReadLineByLine.java:10

    Solution

    To resolve this issue in above path, place the double slash (\) after ‘logging’ as below.

    Example : C:\\Users\\facingissuesonit\\Desktop\\logs\\test.txt

    Recommendations

    We also have some recommendations to resolve similar issues in other places:

    • Always use the path in windows with double slash (\) and linux with backslash (/). In case of path is dynamic and not sure about the OS for deploy of applciations always use File.separator which will convert to accounding to OS.
    • When this exception occured it always show the Index of invalid character in String path that will help you to remove the invalid character from path.

    Conclusion

    In this post you learn about the InvalidPathException and it’s constructor. Also explained one example of InvalidPathException with the solutions of resolving this issue in your code.

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    [Java] Plus Pattern Java Program

    In this “Print Plus Pattern” – We have written Java programs to print/draw Plus pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

    Plus Pattern Example

    Logic: To draw Plus Pattern through Java program, there would be one line of the vertical and horizontal. To draw vertical line just double (2*n) the inserted size and run one outer loop for each rows. Inside of this loop put condition as when i!=n, run internal loop print character if (j=n) else print space. When i=n then print 2*n characters for complete row.

    This post covers following ways to print Plus Pattern:

    • Print Plus Pattern Java Program: Using for Loop
    • Print Plus Pattern Java Program: Using While Loop
    • Print Plus Pattern Java Program: Using Do-While Loop

    Plus Pattern Java Program: For Loop

    This Plus Pattern Java Program is following the below logic:

    1. The outer “for” loop first check the condition ( i<=n*2-1), if this condition is true then it check the if condition (i!=n) is true, then first inner “for” loop will be executed otherwise else part will execure for 2nd “for” loop.
    2. The first inner loop, if the condition (j==n) is true then it will display the symbol otherwise display the spaces. This loop will execute until the condition is satisfies.
    3. The second inner “for” loop will execute if the condition at the outer “for” loop is false, in the loop if condition is true display the symbol as given.
    package _1_patterns.plus;
    
    import java.util.Scanner;
    
    public class PlusPatternForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawPlusPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawPlusPattern(int n, char c) {
    		for (int i = 1; i <= n * 2 - 1; i++) {
    			if (i != n)
    				for (int j = 1; j <= n; j++) {
    					if (j == n)
    						System.out.print(c);
    					System.out.print(" ");
    				}
    			else
    				for (int j = 1; j <= n * 2 - 1; j++) {
    					System.out.print(c);
    				}
    
    			System.out.println();
    		}
    	}
    }
    

    Output

    Enter Pattern Size : 
    9
    Enter Symbol : $
            $ 
            $ 
            $ 
            $ 
            $ 
            $ 
            $ 
            $ 
    $$$$$$$$$$$$$$$$$
            $ 
            $ 
            $ 
            $ 
            $ 
            $ 
            $ 
            $ 
    
    

    Plus Pattern Java Program: While Loop

    This Plus Pattern Java Program is following the below logic:

    1. The outer “while” loop first check the condition ( i<=n*2-1), if this condition is true then it check the if condition (i!=n) is true, then first inner “while” loop will be executed otherwise else part will execute for 2nd “while” loop.
    2. The first inner “while” loop, if the condition (j==n) is true then it will displays the symbol otherwise display the spaces. This loop will execute untill the condition is satisfies.
    3. The second inner “while” loop will execute if the condition at the outer “while” loop is false, in the loop if condition is true display the symbol as given.
    package _1_patterns.plus;
    
    import java.util.Scanner;
    
    public class PlusPatternForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawPlusPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawPlusPattern(int n, char c) {
    		int i = 1;
    		int j;
    		while (i <= n * 2 - 1) {
    			if (i != n) {
    				j = 1;
    				while (j <= n) {
    					if (j == n)
    						System.out.print(c);
    					System.out.print(" ");
    					j++;
    				}
    			} else {
    				j = 1;
    				while (j <= n * 2 - 1) {
    					System.out.print(c);
    					j++;
    				}
    			}
    			System.out.println();
    			i++;
    		}
    	}
    }
    

    Output

    Enter Pattern Size : 
    7
    Enter Symbol : #
          # 
          # 
          # 
          # 
          # 
          # 
    #############
          # 
          # 
          # 
          # 
          # 
          # 
    

    Plus Pattern Java Program: Do-While Loop

    This Plus Pattern Java Program is following the below logic:

    1. The first outer “do-while” loop will execute, then checks the condition (i<=n*2-1).
    2. If condition (i!=n) is true, then first inner “do-while” loop will be executed otherwise second inner “do-while” loop will be executed.
    3. The outer “do-while” loop executes until the condition (i<=n*2-1) is false.

    package _1_patterns.plus;

    import java.util.Scanner;

    public class PlusPatternForLoop {

    public static void main(String[] args) {
    
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter Pattern Size : ");
        int size = sc.nextInt();
    
        System.out.print("Enter Symbol : ");
        char symbol = sc.next().charAt(0);
    
        drawPlusPattern(size, symbol);
    
        // Close Scanner
        sc.close();
    }
    
    private static void drawPlusPattern(int n, char c) {
    int i = 1;
    		int j;
    
    		do {
    			if (i != n) {
    				j = 1;
    				do {
    					if (j == n) {
    						System.out.print(c);
    					}
    					System.out.print(" ");
    					j++;
    				} while (j <= n);
    			} else {
    				j = 1;
    				do {
    					System.out.print(c);
    					j++;
    				} while (j <= n * 2 - 1);
    			}
    			System.out.println();
    			i++;
    		} while (i <= n * 2 - 1);
    }
    }
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : ^
           ^ 
           ^ 
           ^ 
           ^ 
           ^ 
           ^ 
           ^ 
    ^^^^^^^^^^^^^^^
           ^ 
           ^ 
           ^ 
           ^ 
           ^ 
           ^ 
           ^ 
    

    Hope this post helps you to implement the Plus Pattern through Java Program. Please share your comments.

    Happy Learning!!!

    [Java] Square Pattern Java Program

    In this “Print Square Pattern” – We have written Java programs to print/draw square pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

    Square Pattern Example

    This post covers following ways to print Star (X) Pattern:

    • Print Square Pattern Java Program: Using for Loop
    • Print Square Pattern Java Program: Using While Loop
    • Print Square Pattern Java Program: Using Do-While Loop

    Logic: A square will have same number of rows and columns. In this program implemented the logic through outer and inner loop. Outer loop is used for rows and inner loop for columns.

    Square Pattern Java Program: For Loop

    This Square Pattern Java Program is following the below logic:

    1. The outer for loop iterated n times until the condition i<n is false.
    2. The inner for loop iterates n times and display the symbol until the condition j<n is false.
    package _1_patterns.square;
    
    import java.util.Scanner;
    
    public class SquarePatternForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawSquarePattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawSquarePattern(int n, char c) {
    		for (int i = 0; i < n; i++) {
    			for (int j = 0; j < n; j++) {
    				System.out.print(c);
    			}
    			System.out.println();
    		}
    	}
    }
    

    Output

    Enter Pattern Size : 
    10
    Enter Symbol : ^
    ^^^^^^^^^^
    ^^^^^^^^^^
    ^^^^^^^^^^
    ^^^^^^^^^^
    ^^^^^^^^^^
    ^^^^^^^^^^
    ^^^^^^^^^^
    ^^^^^^^^^^
    ^^^^^^^^^^
    ^^^^^^^^^^
    

    Square Pattern Java Program: While Loop

    This Square Pattern Java Program is following the below logic:

    1. The outer while loop iterated n times until the condition i++<n is false.
    2. The inner while loop iterates n times and display the symbol until the condition j++<n is false.
    package _1_patterns.square;
    
    import java.util.Scanner;
    
    public class SquarePatternWhileLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawSquarePattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawSquarePattern(int n, char c) {
    		int i = 0;
    		while (i++ < n) {
    			int j = 0;
    			while (j++ < n)
    			{
    				System.out.print(c);
    			}
    			System.out.println();
    		}
    	}
    }
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : %
    %%%%%%%%
    %%%%%%%%
    %%%%%%%%
    %%%%%%%%
    %%%%%%%%
    %%%%%%%%
    %%%%%%%%
    %%%%%%%%
    

    Square Pattern Java Program: Do-While Loop

    This Square Pattern Java Program is following the below logic:

    1. The outer do-while loop iterated n times until the condition ++i<n is false.
    2. The inner do-while loop iterates n times and display the symbol until the condition ++j<n is false.

    package _1_patterns.square;
    
    import java.util.Scanner;
    
    public class SquarePatternDoWhileLoop {
    
    public static void main(String[] args) {
    
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter Pattern Size : ");
        int size = sc.nextInt();
    
        System.out.print("Enter Symbol : ");
        char symbol = sc.next().charAt(0);
    
        drawSquarePattern(size, symbol);
    
        // Close Scanner
        sc.close();
    }
    
    private static void drawSquarePattern(int n, char c) {
           int i = 0;
    		do {
    			int j = 0;
    			do {
    				System.out.print(c);
    			} while (++j < n);
    			System.out.println();
    		} while (++i < n);
    }
    }
    

    Output

    Enter Pattern Size : 
    7
    Enter Symbol : #
    #######
    #######
    #######
    #######
    #######
    #######
    #######
    

    Hope this post helps you to implement the Square Pattern through Java Program. Please share your comments.

    Happy Learning!!!

    [Java] Right Arrow Pattern Java Program

    In this “Print Right Arrow Pattern” – We have written Java programs to print/draw Right Arrow Pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

    Right Arrow Pattern Example

    This post covers following ways to print Star (X) Pattern:

    • Print Right Arrow Pattern Java Program: Using for Loop
    • Print Right Arrow Pattern Java Program: Using While Loop
    • Print Right Arrow Pattern Java Program: Using Do-While Loop

    Logic: This Right Arrow Pattern logic is implemented mainly in two parts; first outer loop will display the first half of the pattern and second outer loop will display the second half of the pattern. Here outer loop will display the rows and inner loops will display the columns.

    Right Arrow Pattern Java Program: For Loop

    This Right Arrow Pattern Java Program is following the below logic:

    1. First outer for loop condition will checked if it is true then it checks the inner for loop condition if it is true then display space otherwise display symbol which user have given to display.
    2. Inner for loop will execute the code until the condition is false.
    3. Similarly, the condition at 2nd outer for loop is true, then inner for loop will execute until the condition id false. In inner loop “if” condition is true, then it display space otherwise displays symbol which user have given to display.
    package _1_patterns.right_arrow;
    
    import java.util.Scanner;
    
    public class RightArrowPatternForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawRightArrowPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawRightArrowPattern(int n, char c) {
    		for (int i = 0; i < n; i++) {
    			for (int j = 0; j < n; j++) {
    				if (j < i)
    					System.out.print("  ");
    				else
    					System.out.print(c);
    			}
    			System.out.println();
    		}
    		for (int i = 2; i <= n; i++) {
    			for (int j = 0; j < n; j++) {
    				if (j < n - i)
    					System.out.print("  ");
    				else
    					System.out.print(c);
    			}
    			System.out.println();
    		}	
    	}
    }
    

    Output

    Enter Pattern Size : 
    5
    Enter Symbol : $
    $$$$$
      $$$$
        $$$
          $$
            $
          $$
        $$$
      $$$$
    $$$$$
    

    Right Arrow Pattern Java Program: While Loop

    This Right Arrow Pattern Java Program is following the below logic:

    1. The condition at first outer while loop is true, then it comes to the inner loop, the inner loop condition also true then checks the “if” condition, is true, then it displays space otherwise will display symbol. The inner loop will execute the code until condition is false. The 1st outer loop executes the code until the condition is i<n.
    2. Similarly, pointer comes to the next line then second outer while loop will be executed until the condition is false.
    package _1_patterns.rightarrow;
    
    import java.util.Scanner;
    
    public class RightArrowPatternWhileLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawRightArrowPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawRightArrowPattern(int n, char c) {
    		int i = 0;
    		int j;
    		while (i < n) {
    			j = 0;
    			while (j < n) {
    				if (j < i)
    					System.out.print("  ");
    				else
    					System.out.print(c);
    				j++;
    			}
    			System.out.println();
    			i++;
    		}
    		i = 2;
    		while (i <= n) {
    			j = 0;
    			while (j < n) {
    				if (j < n - i)
    					System.out.print("  ");
    				else
    					System.out.print(c);
    				j++;
    			}
    			System.out.println();
    			i++;
    		}
    	}
    }
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : %
    %%%%%%%%
      %%%%%%%
        %%%%%%
          %%%%%
            %%%%
              %%%
                %%
                  %
                %%
              %%%
            %%%%
          %%%%%
        %%%%%%
      %%%%%%%
    %%%%%%%%
    

    Right Arrow Pattern Java Program: Do-While Loop

    This Java Program is following the below logic:

    1. in the first outer do-while loop, it executes the code and then checks the condition i<n, The first outer do-while loop will exceute the code until the condition i<n false.
    2. Similarly, the second outer do-while loop will execute the code until the condition i<n is false.

    package _1_patterns.rightarrow;
    
    import java.util.Scanner;
    
    public class RightArrowPatternDoWhileLoop {
    
    public static void main(String[] args) {
    
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter Pattern Size : ");
        int size = sc.nextInt();
    
        System.out.print("Enter Symbol : ");
        char symbol = sc.next().charAt(0);
    
        drawRightArrowPattern(size, symbol);
    
        // Close Scanner
        sc.close();
    }
    
    private static void drawRightArrowPattern(int n, char c) {
    int i = 0;
    		int j;
    		do {
    			j = 0;
    
    			do {
    				if (j < i)
    					System.out.print("  ");
    				else
    					System.out.print(c);
    				j++;
    			} while (j < n);
    
    			System.out.println();
    			i++;
    
    		} while (i < n);
    		i = 2;
    		do {
    			j = 0;
    			do {
    				if (j < n - i)
    					System.out.print("  ");
    				else
    					System.out.print(c);
    				j++;
    
    			} while (j < n);
    
    			System.out.println();
    			i++;
    		} while (i <= n);
    }
    }
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : #
    ########
      #######
        ######
          #####
            ####
              ###
                ##
                  #
                ##
              ###
            ####
          #####
        ######
      #######
    ########
    

    Hope this post helps you to implement the Right Arrow Pattern through Java Program. Please share your comments.

    Happy Learning!!!

    [Java] Rhombus Pattern Java Program

    In this “Print Rhombus Pattern” – We have written Java programs to print/draw Rhombus pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

    Pattern Example

    This post covers following ways to print Rhombus Pattern:

    • Print Rhombus Pattern Java Program: Using for Loop
    • Print Rhombus Pattern Java Program: Using While Loop
    • Print Rhombus Pattern Java Program: Using Do-While Loop

    Rhombus Pattern Java Program: For Loop

    This Rhombus Java Program is following the below logic:

    1. In this program ask inputs from the user for size of rhombus pattern and symbol to create it.
    2. Outer for loop is used to print number of rows while inner for loops are used to print number of columns.
    3. First inner for loop (int j = 1; j <= n – i; j++) is used to print spaces and it reduce the number of spaces bases on each count of outer loop.
    4. Second inner for loop (int j = 1; j <= n; j++) print the number symbols as entered in size.
    package _1_patterns.rhombus;
    
    import java.util.Scanner;
    
    public class RhombusPatternForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawRhombusPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawRhombusPattern(int n, char c) {
    		for (int i = 1; i <= n; i++) {
    			for (int j = 1; j <= n - i; j++)
    			{
    				System.out.print(" ");
    			}
    			for (int j = 1; j <= n; j++)
    			{
    				System.out.print(c);
    			}
    			System.out.println();
    		}	
    	}
    }
    

    Output

    Enter Pattern Size : 
    6
    Enter Symbol : $
         $$$$$$
        $$$$$$
       $$$$$$
      $$$$$$
     $$$$$$
    $$$$$$
    

    Rhombus Pattern Java Program: While Loop

    This Rhombus Java Program is following the below logic:

    1. Outer while loop is used to print number of rows while inner while loops are used to print number of columns.
    2. First inner while loop (j++ <= n-i) is used to print spaces and it reduce the number of spaces bases on each count of outer loop.
    3. Second inner while loop (j++ <= n) print the number symbols as entered in size.
    package _1_patterns.rhombus;
    
    import java.util.Scanner;
    
    public class RhombusPatternForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawRhombusPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawRhombusPattern(int n, char c) {
    	int i = 1;
    		while (i <= n) {
    			int j = 1;
    			while (j++ <= n - i) {
    				System.out.print(" ");
    			}
    			j = 1;
    			while (j++ <= n) {
    				System.out.print(c);
    			}
    			System.out.println();
    			i++;
    		}
    	}
    }
    

    Output

    Enter Pattern Size : 
    7
    Enter Symbol : #
          #######
         #######
        #######
       #######
      #######
     #######
    #######
    

    Rhombus Pattern Java Program: Do-While Loop

    This Rhombus Java Program is following the below logic:

    1. Outer dowhile loop is used to print number of rows while inner do-while loops are used to print number of columns.
    2. First inner do-while loop (j++ <= n-i) is used to print spaces and it reduce the number of spaces bases on each count of outer loop.
    3. Second inner do-while loop (j++ <= n) print the number symbols as entered in size.

    package _1_patterns.rhombus;
    
    import java.util.Scanner;
    
    public class RhombusPatternForLoop {
    
    public static void main(String[] args) {
    
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter Pattern Size : ");
        int size = sc.nextInt();
    
        System.out.print("Enter Symbol : ");
        char symbol = sc.next().charAt(0);
    
        drawRhombusPattern(size, symbol);
    
        // Close Scanner
        sc.close();
    }
    
    private static void drawRhombusPattern(int n, char c) {
    int i = 1;
    		do {
    			int j = 1;
    			do {
    				System.out.print(" ");
    			} while (j++ <= n - i);
    			j = 1;
    			do {
    				System.out.print(c);
    			} while (++j <= n);
    
    			System.out.println();
    			i++;
    		} while (i <= n);
    }
    }
    

    Output

    Enter Pattern Size : 
    10
    Enter Symbol : ^
              ^^^^^^^^^^
             ^^^^^^^^^^
            ^^^^^^^^^^
           ^^^^^^^^^^
          ^^^^^^^^^^
         ^^^^^^^^^^
        ^^^^^^^^^^
       ^^^^^^^^^^
      ^^^^^^^^^^
     ^^^^^^^^^^
    
    

    Hope this post helps you to implement the Rhombus Pattern through Java Program. Please share your comments.

    Happy Learning!!!

    [Java] Star (X) Pattern Java Program

    In this “Print Star (X) Pattern” – We have written Java programs to print/draw Star (X) pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

    Pattern Example

    This post covers following ways to print Star (X) Pattern:

    • Print Star (X) Pattern Java Program: Using for Loop
    • Print Star (X) Pattern Java Program: Using While Loop
    • Print Star (X) Pattern Java Program : Using Do-While Loop

    Star (X) Pattern Java Program: For Loop

    This Java Program is following the below logic:

    1. Inner for loop iterates from j=1 to k and prints characters if j=i or j=k-i+1 displays “*” (symbol), else display space.
    2. Inner for loop will execute until condition i<=k is false, then it comes to the outer for loop.
    package _1_patterns.xstar;
    
    import java.util.Scanner;
    
    public class XStarPatternForLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawXStarPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawXStarPattern(int n, char c) {
    		int k = n * 2 - 1;
    		for (int i = 1; i <= k; i++) {
    			for (int j = 1; j <= k; j++) {
    				if (j == i || j == k - i + 1) {
    					System.out.print(c);
    				}
    				System.out.print(" ");
    			}
    			System.out.println();
    		}
    	}
    }
    

    Output

    Enter Pattern Size : 
    8
    Enter Symbol : $
    $              $ 
     $            $  
      $          $   
       $        $    
        $      $     
         $    $      
          $  $       
           $        
          $  $       
         $    $      
        $      $     
       $        $    
      $          $   
     $            $  
    $              $ 
    

    Star (X) Pattern Java Program: While Loop

    This Java Program is following the below logic:

    1. While loop first checks the condition i.e i<=k, if it true, then it comes to the inner while loop.
    2. Inner while loop first checks the condition i.e j<=k, then it executes the logic in loop until the condition is false, then pointer come out of the inner loop and goes to the outer loop, this will continue until the condition i<=k is false.
    package _1_patterns.xstar;
    
    import java.util.Scanner;
    
    public class XStarPatternWhileLoop {
    
    	public static void main(String[] args) {
    
    		Scanner sc = new Scanner(System.in);
    
    		System.out.println("Enter Pattern Size : ");
    		int size = sc.nextInt();
    
    		System.out.print("Enter Symbol : ");
    		char symbol = sc.next().charAt(0);
    
    		drawXStarPattern(size, symbol);
    
    		// Close Scanner
    		sc.close();
    	}
    
    	private static void drawXStarPattern(int n, char c) {
    		int i = 1;
    		int j;
    		int k = n * 2 - 1;
    
    		while (i <= k) {
    			j = 1;
    			while (j <= k) {
    				if (j == i || j == k - i + 1) {
    					System.out.print(c);
    				}
    				System.out.print(" ");
    				j++;
    			}
    			System.out.println();
    			i++;
    	}
    }
    

    Output

    Enter Pattern Size : 
    5
    Enter Symbol : @
    @        @ 
     @      @  
      @    @   
       @  @    
        @     
       @  @    
      @    @   
     @      @  
    @        @ 
    

    Star (X) Pattern Java Program: Do-While Loop

    This Java Program is following the below logic:

    1. Inner do-while loop, first the code in the inner loop executes until the condition j<=k is false. It prints symbol for j=1, j=k-i+1. Other than these j values print space.
    2. If the condition false, then pointer comes to outer do-while loop and execute until the condition i<=k is false.
    package _1_patterns.xstar;
    
    import java.util.Scanner;
    
    public class XStarPatternDoWhileLoop {
    public static void main(String[] args) {
    
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter Pattern Size : ");
        int size = sc.nextInt();
    
        System.out.print("Enter Symbol : ");
        char symbol = sc.next().charAt(0);
    
        drawXStarPattern(size, symbol);
    
        // Close Scanner
        sc.close();
    }
    
    private static void drawXStarPattern(int n, char c) {
            int i = 1;
    		int j;
    		int k = n * 2 - 1;
    
    		do {
    			j = 1;
    			do {
    				if (j == i || j == k - i + 1) {
    					System.out.print(c);
    				}
    				System.out.print(" ");
    				j++;
    
    			} while (j <= k);
    			System.out.println();
    			i++;
    		} while (i <= k);
    }
    }
    

    Output

    Enter Pattern Size : 
    6
    Enter Symbol : ^
    ^          ^ 
     ^        ^  
      ^      ^   
       ^    ^    
        ^  ^     
         ^      
        ^  ^     
       ^    ^    
      ^      ^   
     ^        ^  
    ^          ^ 
    

    Hope this post helps you to implement the Start (X) Pattern through Java Program. Please share your comments.

    Happy Learning !!!

    [Solved] SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: “No appropriate protocol (protocol is disabled or cipher suites are inappropriate)

    This issue “SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: “No appropriate protocol (protocol is disabled or cipher suites are inappropriate)” was happening to me when upgrade from jDK 8_271 to JDK_8_341 and MSSQL driver.

    Below are the stacktrace of the issue.

    Stacktrace

    Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "No appropriate protocol (protocol is disabled or cipher suites are inappropriate)".
    	at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1368)
    	at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1412)
    	at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1058)
    	at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:833)
    	at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:716)
    	at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)
    	at java.sql.DriverManager.getConnection(DriverManager.java:664)
    	at java.sql.DriverManager.getConnection(DriverManager.java:208)
    	at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
    	at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
    	at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155)
    	at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120)
    	at org.springframework.batch.item.database.AbstractCursorItemReader.initializeConnection(AbstractCursorItemReader.java:422)
    	... 30 more
    Caused by: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
    	at sun.security.ssl.HandshakeContext.<init>(HandshakeContext.java:171)
    	at sun.security.ssl.ClientHandshakeContext.<init>(ClientHandshakeContext.java:106)
    	at sun.security.ssl.TransportContext.kickstart(TransportContext.java:238)
    	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410)
    	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:389)
    	at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1379)
    	... 41 more
    

    Solutions

    SQL Server JDBC Driver versions are specific to JDK versions. Till JDK_8.271, JDBC driver versions supported as 4.1 however for the latest version JDK_8_341 use the SQL Server JDBC driver 8.4.1.

    In my case this issue got resolved by updating the jar file as below:

    Old Jar : mssql-jdbc4-2.0.jar

    New Jar: mssql-jdbc-8.4.1.jre8.jar

    Please refer below the complete SQLServer JDBC driver support matrix specific to Java/JDK versions.

    https://learn.microsoft.com/en-us/sql/connect/jdbc/microsoft-jdbc-driver-for-sql-server-support-matrix?view=sql-server-ver16#java-and-jdbc-specification-support

    Please share your comments if this solutions help you to resolve this issue.

    Happy Learning !!!

    [Solved] SQLServerException: The TCP/IP connection to the host ABCKXYZ356, port 1345 has failed

    This is most common exception when connecting with database through Spring boot application. It’s happen because of connection failed to the database.

    com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host ABCKXYZ356, port 1345 has failed. Error: "ABCKXYZ356. 
    Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. 
    Make sure that TCP connections to the port are not blocked by a firewall.".    
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:234) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
    at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:285) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
    at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2434) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
    at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:659) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2546) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2216) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2067) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1204) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
    at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:825) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar:na]    
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar:na]    
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar:na]    
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar:na]    
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar:na]    
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-4.0.3.jar:na]

    Reason of Exception

    These are main reason of this Exception:

    • This issue can occurred because of wrong properties configured for database connection.
    • This issue can also occurred if the database is not running.
    • This issue can also occurred if database only allow to access through vpn.

    Solutions

    These are some most common solution to resolve this issue:

    • Verify the connection properties.
    • Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port.
    • Make sure that TCP connections to the port are not blocked by a firewall.
    • Check the vpn connection if DB access allow over the vpn.

    Related Posts

    Your Feedback Motivate Us

    If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

    Happy Learning !!!

    JSON to JAVA Entities Mapping

    In previous topics you learn JSON Overview and syntax, Now you will learn about the mapping between the JAVA and JSON entities mappings. These mapping helpful while encoding and decoding of JSON to Java object.

    Mapping between JSON and JAVA entities

    These are mapping between JSON and JAVA object

    JSONJAVA
    stringjava.lang.String
    numberjava.lang.Number
    true | falsejava.lang.Boolen
    nullnull
    arrayjava.util.List
    objectjava.ulit.Map
    JSON and JAVA object mapping

    Please follow these example to map values. JSON Data Types & Syntax

    Happy Learning !!!

    Write a program to convert a non-negative integer number to its English words representation

    In this program converting Non-negative numbers to English words through Java Program. You can use the same logic to implement with other languages like C, C++, C#, Python, etc.

    This program is most frequently asked in programming label tests or interviews to check your logical skills. You can also utilize the same code while generating invoices, bills, reports where want to show sum, average, gross total etc. in form of words.

    For Example :

    InputOutput
    123One Hundred Twenty Three
    1234One Thousand Two Hundred Thirty Four
    12345Twelve Thousand Three Hundred Forty Five
    123456One Hundred Twenty Three Thousand Four Hundred Fifty Six
    1234567One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven
    1234568One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Eight
    12345670Twelve Million Three Hundred Forty Five Thousand Six Hundred Seventy
    123456709One Hundred Twenty Three Million Four Hundred Fifty Six Thousand Seven Hundred Nine
    1234567090One Billion Two Hundred Thirty Four Million Five Hundred Sixty-Seven Thousand Ninety
    Program to convert numbers to English Words

    Java Program

    To convert a number to English word core logic is to check 10th position of the number the add words for the same. Based on the range between billion to thousand then take reminder and add word (thousand, million or billion) etc. then further dividend of the number by the range and further pass for convert as long as not reaching to less than thousand. Finally, when numbers reach to between 1-20 take the words from map 1-20 range.

    Source Code:

    package programming;
    
    import java.text.DecimalFormat;
    
    public class NNNumberToWordExample {
    	// array of string type for one digit numbers
    	private static final String[] doubleDigits = { "", " Ten", " Twenty", " Thirty", " Forty", " Fifty", " Sixty",
    			" Seventy", " Eighty", " Ninety" };
    	// array of string for two digits numbers
    	private static final String[] singleDigit = { "", " One", " Two", " Three", " Four", " Five", " Six", " Seven",
    			" Eight", " Nine", " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen",
    			" Seventeen", " Eighteen", " Nineteen" };
    
    	// converts a number to words (up to 1000)
    	private static String convertUptoThousand(int number) {
    		String soFar;
    		if (number % 100 < 20) {
    			soFar = singleDigit[number % 100];
    			number = number / 100;
    		} else {
    			soFar = singleDigit[number % 10];
    			number = number / 10;
    			soFar = doubleDigits[number % 10] + soFar;
    			number = number / 10;
    		}
    		if (number == 0)
    			return soFar;
    		return singleDigit[number] + " Hundred " + soFar;
    	}
    
    	// converts a long number (0 to 999999999) to string
    	public static String convertNumberToWord(long number) {
    		// checks whether the number is zero or not if number is zero return zero
    		if (number == 0) {
    			return "zero";
    		}
    		// convert long value to string
    		String num = Long.toString(number);
    		// for creating a mask padding with "0"
    		String pattern = "000000000000";
    		/**
    		 * Convert to DecimalFormat using the specified pattern and also provides the
    		 * symbols to default locale
    		 */
    		DecimalFormat decimalFormat = new DecimalFormat(pattern);
    		// format a number of the DecimalFormat
    		num = decimalFormat.format(number);
    		/**
    		 * format: XXXnnnnnnnnn the subString() method returns a new string that is a
    		 * substring of this string the substring begins at the specified beginIndex and
    		 * extends to the character at index endIndex - 1 the parseInt() method converts
    		 * the string into integer
    		 */
    		int billions = Integer.parseInt(num.substring(0, 3));
    		// format to: nnnXXXnnnnnn
    		int millions = Integer.parseInt(num.substring(3, 6));
    		// format to: nnnnnnXXXnnn
    		int hundredThousands = Integer.parseInt(num.substring(6, 9));
    		// format to: nnnnnnnnnXXX
    		int thousands = Integer.parseInt(num.substring(9, 12));
    
    		String tradBillions;
    
    		switch (billions) {
    		case 0:
    			tradBillions = "";
    			break;
    		case 1:
    			tradBillions = convertUptoThousand(billions) + " Billion ";
    			break;
    		default:
    			tradBillions = convertUptoThousand(billions) + " Billion ";
    		}
    
    		String result = tradBillions;
    		String tradMillions;
    		switch (millions) {
    		case 0:
    			tradMillions = "";
    			break;
    		case 1:
    			tradMillions = convertUptoThousand(millions) + " Million ";
    			break;
    		default:
    			tradMillions = convertUptoThousand(millions) + " Million ";
    		}
    		result = result + tradMillions;
    
    		String tradHundredThousands;
    		switch (hundredThousands) {
    		case 0:
    			tradHundredThousands = "";
    			break;
    		case 1:
    			tradHundredThousands = "One Thousand ";
    			break;
    		default:
    			tradHundredThousands = convertUptoThousand(hundredThousands) + " Thousand ";
    		}
    		result = result + tradHundredThousands;
    
    		String tradThousand;
    		tradThousand = convertUptoThousand(thousands);
    		result = result + tradThousand;
    
    		// removing extra space if any
    		return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
    	}
    
    	public static void main(String args[]) {
    		// Test cases to convert number to words
    		System.out.println(convertNumberToWord(5));
    		System.out.println(convertNumberToWord(89));
    		System.out.println(convertNumberToWord(656));
    		System.out.println(convertNumberToWord(1301));
    		System.out.println(convertNumberToWord(13512));
    		System.out.println(convertNumberToWord(567319));
    		System.out.println(convertNumberToWord(90908890));
    		System.out.println(convertNumberToWord(2000000000));
    		System.out.println(convertNumberToWord(569999999));
    		System.out.println(convertNumberToWord(3233000000L));
    		System.out.println(convertNumberToWord(5000000));
    		System.out.println(convertNumberToWord(333333333));
    		System.out.println(convertNumberToWord(5000400));
    		System.out.println(convertNumberToWord(600000));
    		System.out.println(convertNumberToWord(4000000));
    	}
    }
    

    Output

    Five
    Eighty Nine
    Six Hundred Fifty Six
    One Thousand Three Hundred One
    Thirteen Thousand Five Hundred Twelve
    Five Hundred Sixty Seven Thousand Three Hundred Nineteen
    Ninety Million Nine Hundred Eight Thousand Eight Hundred Ninety
    Two Billion 
    Five Hundred Sixty Nine Million Nine Hundred Ninety Nine Thousand Nine Hundred Ninety Nine
    Three Billion Two Hundred Thirty Three Million 
    Five Million 
    Three Hundred Thirty Three Million Three Hundred Thirty Three Thousand Three Hundred Thirty Three
    Five Million Four Hundred 
    Six Hundred Thousand 
    Four Million 
    

    Hope this program help you and clear your logics. Please share in comments.

    Happy Learning !!!

    [Solved] SQLServerException: Arithmetic overflow error converting float to data type numeric :scientific value

    This SQLServerException is common with the applications using the MSSQL database. Once it occurs it generate the below stackTrace.

    Exception Stack Trace

    com.microsoft.sqlserver.jdbc.SQLServerException: Arithmetic overflow error converting float to data type numeric.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
    
    

    Reason of Exception

    This issue occurred when your precision and scale argument is set two small for decimal column. For Example: decimal(3,2) or float(3,2) . It will float allow maximum value as 9.99

    Basically the first argument (precision) is the max number of digits (in this case 3) and the second argument (scale) is the number of digits to the right of the decimal point, which always takes away from the number of digits you can have to the left of the decimal point. So in this case, 3-2 = 1 digit allowed to the left of the decimal point, which is why allow max value can only be 9.99.

    if you will try numeric value more than this size Ex : 10.9 then SQL server will throw exception as “SQLServerException: Arithmetic overflow error converting float to data type numeric” because size is more than the defined precision and scale of decimal point.

    Note : This issue can also be occurred when you are trying to insert big values in form of scientific notation Ex: 1.5e100 because it’s precision value is high so throw exception.

    Solutions

    You can follow any of these processes to resolve this issue:

    • Increase the precision and scale of decimal of your column based on your business requirement.
    • Convert the column type as float value so that accept values as per the set precision and scale.
    • You can also use try_cast also to truncate and change the type of passing value.

    Hope these processes resolved this issue. Please share your response in comments.

    Happy Learning !!!

    [Solved] SQLServerException: Arithmetic overflow error converting float to data type numeric

    This SQLServerException is common with the applications using the MSSQL database. Once it occurs it generate the below stackTrace.

    Exception Stack Trace

    com.microsoft.sqlserver.jdbc.SQLServerException: Arithmetic overflow error converting float to data type numeric.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
    
    

    Reason of Exception

    This issue occurred when your precision and scale argument is set two small for decimal column. For Example: NUMERIC(3,2) or DECIMAL(3,2) . It will allow maximum value as 9.99

    Basically the first argument (precision) is the max number of digits (in this case 3) and the second argument (scale) is the number of digits to the right of the decimal point, which always takes away from the number of digits you can have to the left of the decimal point. So in this case, 3-2 = 1 digit allowed to the left of the decimal point, which is why allow max value can only be 9.99.

    if you will try numeric value more than this size Ex : 10.9 then SQL server will throw exception as “SQLServerException: Arithmetic overflow error converting float to data type numeric” because size is more than the defined precision and scale of decimal point.

    Solutions

    You can follow any of these processes to resolve this issue:

    • Increase the precision and scale of decimal of your column based on your business requirement.
    • Convert the column type as float value so that accept values as per the set precision and scale.

    Hope these processes resolved this issue. Please share your response in comments.

    Happy Learning !!!

    [Solved] SQLServerException: String or binary data would be truncated

    This SQLServerException is common with the applications using the MSSQL database. Once it occurs it generate the below stackTrace.

    Exception Stack Trace

    com.microsoft.sqlserver.jdbc.SQLServerException: String or binary data would be truncated. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)

    Reason of Exception

    This exception occurred when you are trying to insert text in a column of type varchar which is more than the size of defined column size then SQL server through this exception “SQLServerException: String or binary data would be truncated“.

    Solutions

    You can follow any of these processes to resolve this issue:

    • Apply validation for text length on the source frontend/client where you in insert the values. It should be less than or equal to size of column.
    • Apply truncation on text before inserting to the database and it should be less than the column size.
    • Increase the sufficient size of the column based on you requirement to resolve this issue.

    Hope these processes resolved this issue. Please share your response in comments.

    Happy Learning !!!

    LIQUIBASE Spring Boot Properties

    LIQUIBASE is a provider of Spring Boot Data for handling database schemas operations. LIQUIBASE is an Open Source tool which keep track of database schema script revisions. It can handle variety of database types and accepts a variety of file formats for defining the database structures.

    See Also:

    <dependency>
    			<groupId>org.liquibase</groupId>
    			<artifactId>liquibase-core</artifactId>
    </dependency>
    

    After adding LIQUIBASE dependencies in your application it will automatically download and add the required other dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

    Liquibase Configuration Properties

    Spring Boot load these properties in LiquibaseProperties class.

    NameDefault ValueDescription
    liquibase.change-logclasspath:/db/ changelog/db.
    changelog-master.yaml
    Change log configuration path.
    liquibase.check-change-log-locationtrueCheck the change log location exists.
    liquibase.contexts Comma-separated list of runtime contexts to use.
    liquibase.default-schema Default database schema.
    liquibase.drop-firstfalseDrop the database schema first.
    liquibase.enabledtrueEnable liquibase support.
    liquibase.labels Comma-separated list of runtime labels to use.
    liquibase.parameters.* Change log parameters.
    liquibase.password Login password of the database to migrate.
    liquibase.rollback-file File to rollback SQL statements will be written when an update is performed.
    liquibase.url JDBC url of the database to migrate. Incase not set then use the primary configured data source.
    liquibase.user Login user of the database to migrate.
    LIQUIBASE Spring Boot Properties

    References

    https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

    Happy Learning !!!

    Cassandra Spring Boot Properties

    Apache Cassandra is a provider of Spring Boot Data for handling NoSQL database operations. Apache Cassandra is a NoSQL distributed database for managing large amounts of data across many servers (clusters) while providing high availability at the cost of decreased consistency. Cassandra high availability is achieved by replicating data to multiple nodes over cluster and allow one or more nodes to go down so that transaction will continue till that point even one server is running.

    To use Apache Cassandra in your Spring boot application you have to add this Cassandra starter in your pom.xml .

    <dependency>
             <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-cassandra</artifactId>
            <version>2.0.0.M7</version>
    </dependency>
    

    After adding Cassandra Database starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

    Cassandra Configuration Properties

    Spring Boot load these properties in CassandraProperties class.

    NameDefault ValueDescription
    spring.data.cassandra.cluster-name Cassandra cluster Name.
    spring.data.cassandra.compression Compression supported by the Cassandra binary protocol.
    spring.data.cassandra.connect-timeout-millis Socket option: connection time out.
    spring.data.cassandra.consistency-level Queries consistency level.
    spring.data.cassandra.contact-pointslocalhostComma-separated cluster node addresses.
    spring.data.cassandra.fetch-size Queries default fetch size.
    spring.data.cassandra.keyspace-name Keyspace name to use.
    spring.data.cassandra.load-balancing-policy Class name of the load balancing policy.
    spring.data.cassandra.port Port of the Cassandra server.
    spring.data.cassandra.password Login password of the server.
    spring.data.cassandra.read-timeout-millis Socket option: read time out.
    spring.data.cassandra.reconnection-policy Reconnection policy class.
    spring.data.cassandra.repositories.enabled Enable Cassandra repositories.
    spring.data.cassandra.retry-policy Class name of the retry policy.
    spring.data.cassandra.serial-consistency-level Queries serial consistency level.
    spring.data.cassandra.schema-actionnoneSchema action to take at startup.
    spring.data.cassandra.sslfalseEnable SSL support.
    spring.data.cassandra.username Login user of the server.
    Cassandra Spring Boot Properties

    References

    https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

    Happy Learning !!!

    Couchbase Spring Boot Properties

    Couchbase is a provider of Spring Boot for handling NoSQL database operations through JSON. Couchbase is NoSQL document oriented distributed database over the cloud or on- premises which perform transactions by JSON and provide unmatched versatility, performance and scalability. To use Couchbase in your Spring boot application you have to add this Couchbase starter in your pom.xml .

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-couchbase</artifactId>
        <version>2.6.3</version>
    </dependency>
    

    After adding Couchbase Database starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

    Data Couchbase Configuration Properties

    Spring Boot load these properties in CouchbaseDataProperties class.

    NameDefault ValueDescription
    spring.data.couchbase.auto-indexfalsecreate views and indexes automatically.
    spring.data.couchbase.consistencyread-your-own-writesBy default Consistency to apply on generated queries.
    spring.data.couchbase.repositories.enabledtrueEnable Couchbase repositories.
    Data Couch Spring Boot properties

    Couchbase Configuration Properties

    Spring Boot load these properties in CouchbaseProperties class.

    NameDefault ValueDescription
    spring.couchbase.bootstrap-hosts Couchbase nodes host/IP address to bootstrap from.
    spring.couchbase.bucket.namedefaultbucket name connect to.
    spring.couchbase.bucket.password bucket password.
    spring.couchbase.env.endpoints.key-value1Number of sockets per node for each Key/value service.
    spring.couchbase.env.endpoints.query1Number of sockets per node for each Query (N1QL) service.
    spring.couchbase.env.endpoints.view1Number of sockets per node for each view service.
    spring.couchbase.env.ssl.enabled Enable SSL support. Enabled automatically if a “keyStore” is provided otherwise specified otherwise.
    spring.couchbase.env.ssl.key-store Path to JVM key store which holds the certificates.
    spring.couchbase.env.ssl.key-store-password Password used to access the key store.
    spring.couchbase.env.timeouts.connect5000Bucket connections timeout. (in milliseconds)
    spring.couchbase.env.timeouts.key-value2500Blocking operations performed on a key timeout.( in milliseconds)
    spring.couchbase.env.timeouts.query7500N1QL query operations timeout.( in milliseconds)
    spring.couchbase.env.timeouts.socket-connect1000Socket connect connections timeout.( in milliseconds).
    spring.couchbase.env.timeouts.view7500Regular and geospatial view operations timeout. (in milliseconds).
    Couchbase Spring Boot Properties

    References

    https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

    Happy Learning !!!

    SOLR Spring Boot Properties

    Apache SOLR is a provider of Spring Boot for handling search and indexing of data operations on SOLR content for web. SOLR is a Full Text search engine for content management and also provide REST based SOLR APIs for operations. To use SOLR in your Spring boot application you have to add this SOLR starter in your pom.xml .

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-solr</artifactId>
        <version>2.4.12</version>
    </dependency>
    

    After adding SOLR starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

    SOLR Configuration Properties

    Spring Boot load these properties in SolrProperties class.

    NameDefault ValueDescription
    spring.data.solr.hosthttp://127.0.0.1:8983/solrSolr host. Ignored if “zk-host” is set.
    spring.data.solr.repositories.enabledtrueEnable Solr repositories.
    spring.data.solr.zk-host ZooKeeper host address i.e HOST:PORT.
    SOLR Spring Boot Properties

    References

    https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

    Happy Learning !!!

    Elasticsearch Spring Boot Properties

    Elasticsearch is a provider of Spring Boot for handling search and CRUD operations in Elastic Search. Elasticsearch is a Full Text search engine and also provide REST based Elasticsearch APIs for operations. To use Elastic Search in your Spring boot application you have to add this Elasticsearch starter in your pom.xml .

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    

    After adding Elasticsearch starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

    ElasticSearch Configuration Properties

    Spring Boot load these properties in ElasticsearchProperties class.

    NameDefault ValueDescription
    spring.data.elasticsearch.cluster-nameelasticsearchcluster name.
    spring.data.elasticsearch.cluster-nodes Comma-separated cluster node addresses. If not specified, starts a client node.
    spring.data.elasticsearch.properties.* Additional properties used to configure the client.
    spring.data.elasticsearch.repositories.enabledtrueEnable Elasticsearch repositories.
    Elastic Search Spring Boot Properties

    JEST (Elasticsearch HTTP client) Configuration Properties

    Spring Boot load these properties in JestProperties class.

    NameDefault ValueDescription
    spring.elasticsearch.jest.connection-timeout3000Connection timeout in milliseconds.
    spring.elasticsearch.jest.password Login password.
    spring.elasticsearch.jest.proxy.host Proxy host the HTTP client to use.
    spring.elasticsearch.jest.proxy.port Proxy port the HTTP client to use.
    spring.elasticsearch.jest.read-timeout3000Read timeout. (in milliseconds)
    spring.elasticsearch.jest.urishttp://localhost:9200Comma-separated Elasticsearch instances to use.
    spring.elasticsearch.jest.username Login user.
    JEST/Elastic Search Client Spring Boot Properties

    References

    https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

    Happy Learning !!!

    MongoDB Spring Boot Properties

    MongoDB is a provider of Spring Boot for handling NoSQL database operations. To use MongoDB  in your Spring boot application you have to add this MongoDB starter in your pom.xml .

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-mongodb</artifactId>
            </dependency>
    

    After adding MongoDB starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

    Embedded MongoDB Configuration Properties

    Spring Boot load these properties in EmbeddedMongoProperties class.

    NameDefault ValueDescription
    spring.mongodb.embedded.featuresSYNC_DELAYComma-separated features to enable.
    spring.mongodb.embedded.storage.database-dir Directory used for data storage.
    spring.mongodb.embedded.storage.oplog-size Maximum size of the oplog in megabytes.
    spring.mongodb.embedded.storage.repl-set-name Name of the replica set.
    spring.mongodb.embedded.version2.6.10Version of Mongo to use.
    MongoDB Embedded Spring Boot Properties

    MongoDB Configuration Properties

    Spring Boot load these properties in MongoProperties class.

    NameDefault ValueDescription
    spring.data.mongodb.authentication-database Authentication database name.
    spring.data.mongodb.databasetestDatabase name.
    spring.data.mongodb.field-naming-strategy USe Fully qualified name of the FieldNamingStrategy.
    spring.data.mongodb.grid-fs-database GridFS database name.
    spring.data.mongodb.hostlocalhostMongo server host.
    spring.data.mongodb.password Login password of the mongo server.
    spring.data.mongodb.port27017Mongo server port.
    spring.data.mongodb.repositories.enabledtrueEnable Mongo repositories.
    spring.data.mongodb.urimongodb://localhost/testMongo database URI.host and port are ignored when setting it.
    spring.data.mongodb.username Login user of the mongo server.
    MongoDB Spring Boot Properties

    References

    https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

    Neo4J Spring Boot Properties

    Neo4J is a provider of Spring Boot for handling Graphical database.  Neo4J is a graphical datbase where need to represent stored data in graphical relational forms. You can add Neo4J  in your Spring boot application by adding Neo4J starter in your pom.xml (Maven) or build.gradle (Gradle).

    Maven

    <dependency>
            <groupId>org.neo4j.driver</groupId>
            <artifactId>neo4j-java-driver-spring-boot-starter</artifactId>
            <version>4.3.6.0</version>
    </dependency>
    

    Gradle

    dependencies {
        compile 'org.neo4j.driver:neo4j-java-driver-spring-boot-starter:4.3.6.0'
    }
    

    After adding Neo4J starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

    Neo4j Configuration Properties

    Spring Boot load these properties in Neo4jProperties class.

    NameDefault ValueDescription
    spring.data.neo4j.compiler Compiler to use.
    spring.data.neo4j.embedded.enabledtrueEnable embedded mode when embedded driver is available.
    spring.data.neo4j.password Login password of the server.
    spring.data.neo4j.repositories.enabledtrueEnable Neo4j repositories.
    spring.data.neo4j.session.scopesingletonScope (lifetime) of the session.
    spring.data.neo4j.uri URI used by the driver detected by default.
    spring.data.neo4j.username Login user of the server.
    NEO4J Spring Boot Properties

    References

    https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

    Happy Learning !!!

    ATOMIKOS Spring Boot Properties

    ATOMIKOS is a provider of Spring Boot for handling transactions atomicity in global transactions involving heterogeneous components. To use ATOMIKOS transaction manager in your Spring boot application you have to add this ATOMIKOS starter in your pom.xml .

    <dependency>
          <groupId>com.atomikos</groupId>
          <artifactId>transactions-spring-boot-starter</artifactId>
       </dependency>
    

    After adding ATOMIKOS starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

    Atomikos Configuration Properties

    Spring Boot load these properties in AtomikosProperties class.

    NameDefault ValueDescription
    spring.jta.atomikos.connectionfactory.borrow-connection-timeout30Timeout for borrowing connections from the pool. (in seconds)
    spring.jta.atomikos.connectionfactory.ignore-session-transacted-flagtrueSet to ignore the transacted flag when creating session.
    spring.jta.atomikos.connectionfactory.local-transaction-modefalseSet local transactions are desired.
    spring.jta.atomikos.connectionfactory.maintenance-interval60The time between runs of the pool’s maintenance thread. (in seconds).
    spring.jta.atomikos.connectionfactory.max-idle-time60The time after which connections are cleaned up from the pool. (in seconds)
    spring.jta.atomikos.connectionfactory.max-lifetime0The time that a connection can be pooled for before being destroyed. 0 denotes no limit.(in seconds)
    spring.jta.atomikos.connectionfactory.max-pool-size1The maximum pool size.
    spring.jta.atomikos.connectionfactory.min-pool-size1The minimum pool size.
    spring.jta.atomikos.connectionfactory.reap-timeout0The reap timeout for borrowed connections. 0 denotes no limit.( in seconds)
    spring.jta.atomikos.connectionfactory.unique-resource-namejmsConnectionFactoryThe unique name used to identify the resource during recovery.
    spring.jta.atomikos.datasource.borrow-connection-timeout30Timeout for borrowing connections from the pool. (in seconds)
    spring.jta.atomikos.datasource.default-isolation-level Default isolation level of connections provided by the pool.
    spring.jta.atomikos.datasource.login-timeout Timeout for establishing a database connection.(in seconds)
    spring.jta.atomikos.datasource.maintenance-interval60The time between runs of the pool’s maintenance thread.(in seconds)
    spring.jta.atomikos.datasource.max-idle-time60The time after which connections are cleaned up from the pool.(in seconds)
    spring.jta.atomikos.datasource.max-lifetime0The time that a connection can be pooled for before being destroyed. 0 denotes no limit.(in seconds)
    spring.jta.atomikos.datasource.max-pool-size1The maximum pool size.
    spring.jta.atomikos.datasource.min-pool-size1The minimum pool size.
    spring.jta.atomikos.datasource.reap-timeout0The reap timeout for borrowed connections. 0 denotes no limit.(in seconds)
    spring.jta.atomikos.datasource.test-query SQL query or statement used to validate a connection before returning it.
    spring.jta.atomikos.datasource.unique-resource-namedataSourceThe unique name used to identify the resource during recovery.
    spring.jta.atomikos.properties.checkpoint-interval500Interval between checkpoints.
    spring.jta.atomikos.properties.default-jta-timeout10000Default timeout for JTA transactions.
    spring.jta.atomikos.properties.enable-loggingtrueEnable disk logging.
    spring.jta.atomikos.properties.force-shutdown-on-vm-exitfalseSpecify if a VM shutdown should trigger forced shutdown of the transaction core.
    spring.jta.atomikos.properties.log-base-dir Directory in which the log files should be stored.
    spring.jta.atomikos.properties.log-base-nametmlogTransactions log file base name.
    spring.jta.atomikos.properties.max-actives50Maximum active transactions.
    spring.jta.atomikos.properties.max-timeout300000Maximum timeout that can be allowed for transactions. (in milliseconds)
    spring.jta.atomikos.properties.serial-jta-transactionstrueSpecify if sub-transactions should be joined when possible.
    spring.jta.atomikos.properties.service Transaction manager implementation that should be started.
    spring.jta.atomikos.properties.threaded-two-phase-committrueUse different (and concurrent) threads for two-phase commit on the resources.
    spring.jta.atomikos.properties.transaction-manager-unique-name Transaction manager’s unique name.
    ATOMIKOS Spring Boot Properties

    References

    https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

    Happy Leaning !!!

    BITRONIX Spring Boot Properties

    BITRONIX is a provider of Spring Boot for handling distributed transaction. To use BITRONIX transaction manager in your Spring boot application you have to add this BITRONIX starter in your pom.xml .

    <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-jta-bitronix</artifactId>
     </dependency>
    

    After adding BITRONIX starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

    BiTronix Configuration Properties

    NameDefault ValueDescription
    spring.jta.bitronix.connectionfactory.acquire-increment1Number of connections to create when pool grow.
    spring.jta.bitronix.connectionfactory.acquisition-interval1Time to wait before trying to acquire a connection again after an invalid connection was acquired.(in second)
    spring.jta.bitronix.connectionfactory.acquisition-timeout30Timeout for acquiring connections from the pool. (in second)
    spring.jta.bitronix.connectionfactory.allow-local-transactionstrueSet the transaction manager should allow mixing XA and non-XA transactions.
    spring.jta.bitronix.connectionfactory.apply-transaction-timeoutfalseSet the transaction timeout should be set on the XAResource when it is enlisted.
    spring.jta.bitronix.connectionfactory.automatic-enlisting-enabledtrueSet resources should be enlisted and delisted automatically
    spring.jta.bitronix.connectionfactory.cache-producers-consumerstrueSet produces and consumers should be cached.
    spring.jta.bitronix.connectionfactory.defer-connection-releasetrueSet the provider can run many transactions on the same connection and supports transaction interleaving.
    spring.jta.bitronix.connectionfactory.ignore-recovery-failuresfalseSet recovery failures should be ignored.
    spring.jta.bitronix.connectionfactory.max-idle-time60The time after which connections are cleaned up from the pool.(in second)
    spring.jta.bitronix.connectionfactory.max-pool-size10The maximum pool size. 0 denotes no limit.
    spring.jta.bitronix.connectionfactory.min-pool-size0The minimum pool size.
    spring.jta.bitronix.connectionfactory.password The password to use to connect to the JMS provider.
    spring.jta.bitronix.connectionfactory.share-transaction-connectionsfalseSet connections in the ACCESSIBLE state can be shared within the context of a transaction.
    spring.jta.bitronix.connectionfactory.test-connectionstrueSet connections should be tested when acquired from the pool.
    spring.jta.bitronix.connectionfactory.two-pc-ordering-position1The position that this resource should take during two-phase commit (always first is Integer.MIN_VALUE, always last is Integer.MAX_VALUE).
    spring.jta.bitronix.connectionfactory.unique-namejmsConnectionFactoryThe unique name used to identify the resource during recovery.
    spring.jta.bitronix.connectionfactory.use-tm-jointrue Set TMJOIN should be used when starting XAResources.
    spring.jta.bitronix.connectionfactory.user The user to use to connect to the JMS provider.
    spring.jta.bitronix.datasource.acquire-increment1Number of connections to create when growing the pool.
    spring.jta.bitronix.datasource.acquisition-interval1Time to wait before trying to acquire a connection again after an invalid connection was acquired.(in second)
    spring.jta.bitronix.datasource.acquisition-timeout30Timeout for acquiring connections from the pool. (in second)
    spring.jta.bitronix.datasource.allow-local-transactionstrueSet the transaction manager should allow mixing XA and non-XA transactions.
    spring.jta.bitronix.datasource.apply-transaction-timeoutfalseSet the transaction timeout should be set on the XAResource when it is enlisted.
    spring.jta.bitronix.datasource.automatic-enlisting-enabledtrueSet resources should be enlisted and delisted automatically.
    spring.jta.bitronix.datasource.cursor-holdability The default cursor holdability for connections.
    spring.jta.bitronix.datasource.defer-connection-releasetrueSet the database can run many transactions on the same connection and supports transaction interleaving.
    spring.jta.bitronix.datasource.enable-jdbc4-connection-test Set Connection.isValid() is called when acquiring a connection from the pool.
    spring.jta.bitronix.datasource.ignore-recovery-failuresfalseSet recovery failures should be ignored.
    spring.jta.bitronix.datasource.isolation-level The default isolation level for connections.
    spring.jta.bitronix.datasource.local-auto-commit The default auto-commit mode for local transactions.
    spring.jta.bitronix.datasource.login-timeout Timeout for establishing a database connection.(in second)
    spring.jta.bitronix.datasource.max-idle-time60The time after which connections are cleaned up from the pool.(in second)
    spring.jta.bitronix.datasource.max-pool-size10The maximum pool size. 0 denotes no limit.
    spring.jta.bitronix.datasource.min-pool-size0The minimum pool size.
    spring.jta.bitronix.datasource.prepared-statement-cache-size0The target size of the prepared statement cache. 0 disables the cache.
    spring.jta.bitronix.datasource.share-transaction-connectionsfalseSet connections in the ACCESSIBLE state can be shared within the context of a transaction.
    spring.jta.bitronix.datasource.test-query SQL query or statement used to validate a connection before returning it.
    spring.jta.bitronix.datasource.two-pc-ordering-position1The position that this resource should take during two-phase commit (always first is Integer.MIN_VALUE, always last is Integer.MAX_VALUE).
    spring.jta.bitronix.datasource.unique-namedataSourceThe unique name used to identify the resource during recovery.
    spring.jta.bitronix.datasource.use-tm-jointrue Set TMJOIN should be used when starting XAResources.
    spring.jta.bitronix.properties.allow-multiple-lrcfalseAllow multiple LRC resources to be enlisted into the same transaction.
    spring.jta.bitronix.properties.asynchronous2-pcfalseEnable asynchronously execution of two phase commit.
    spring.jta.bitronix.properties.background-recovery-interval-seconds60Interval at which to run the recovery process in the background.(in seconds)
    spring.jta.bitronix.properties.current-node-only-recoverytrueRecover only the current node.
    spring.jta.bitronix.properties.debug-zero-resource-transactionfalseLog the creation and commit call stacks of transactions executed without a single enlisted resource.
    spring.jta.bitronix.properties.default-transaction-timeout60Default transaction timeout.(in second)
    spring.jta.bitronix.properties.disable-jmxfalseEnable JMX support.
    spring.jta.bitronix.properties.exception-analyzer Set the fully qualified name of the exception analyzer implementation to use.
    spring.jta.bitronix.properties.filter-log-statusfalseEnable filtering of logs so that only mandatory logs are written.
    spring.jta.bitronix.properties.force-batching-enabledtrueSet if disk forces are batched.
    spring.jta.bitronix.properties.forced-write-enabledtrueSet if logs are forced to disk.
    spring.jta.bitronix.properties.graceful-shutdown-interval60Maximum amount of seconds the TM will wait for transactions to get done before aborting them at shutdown time.
    spring.jta.bitronix.properties.jndi-transaction-synchronization-registry-name JNDI name of the TransactionSynchronizationRegistry.
    spring.jta.bitronix.properties.jndi-user-transaction-name JNDI name of the UserTransaction.
    spring.jta.bitronix.properties.journaldiskName of the journal. Can be ‘disk’, ‘null’ or a class name.
    spring.jta.bitronix.properties.log-part1-filenamebtm1.tlogName of the first fragment of the journal.
    spring.jta.bitronix.properties.log-part2-filenamebtm2.tlogName of the second fragment of the journal.
    spring.jta.bitronix.properties.max-log-size-in-mb2Maximum size in megabytes of the journal fragments.
    spring.jta.bitronix.properties.resource-configuration-filename ResourceLoader configuration file name.
    spring.jta.bitronix.properties.server-id ASCII ID that must uniquely identify this TM instance. Default to the machine’s IP address.
    spring.jta.bitronix.properties.skip-corrupted-logsfalseSkip corrupted transactions log entries.
    spring.jta.bitronix.properties.warn-about-zero-resource-transactiontrueLog a warning for transactions executed without a single enlisted resource.
    BITRONIX Spring Boot Properties

    References

    https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

    Happy Learning !!!

    NARAYANA Spring Boot Properties

    Narayana is a popular open source JTA transaction manager implementation supported by Red Hat. To use Narayana JTA in your Spring Boot application you can use You can use the narayana-spring-boot-starter starter to add the appropriate Narayana dependencies to your application.

    NARAYANA pom.xml Dependencies

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jta-narayana</artifactId>
    </dependency>
    

    Spring Boot automatically configures Narayana with default values and post-processes your beans to ensure that startup and shutdown ordering is correct.

    NARAYANA Spring Boot Properties

    Spring Boot load these properties in NarayanaProperties class with default values you can overwrite these values in your application application.properties/ application.yaml.

    NameDefault ValueDescription
    spring.jta.narayana.default-timeout60Transaction timeout.(in second)
    spring.jta.narayana.expiry-scannerscom.arjuna.ats.internal. arjuna.recovery. ExpiredTransactionStatusManagerScannerComma-separated list of expiry scanners.
    spring.jta.narayana.log-dir Transaction object store directory.
    spring.jta.narayana.one-phase-committrueEnable one phase commit optimisation.
    spring.jta.narayana.periodic-recovery-period120Interval in which periodic recovery scans are performed.(in second)
    spring.jta.narayana.recovery-backoff-period10Back off period between first and second phases of the recovery scan.(in second)
    spring.jta.narayana.recovery-db-pass Database password for recovery manager.
    spring.jta.narayana.recovery-db-user Database username for recovery manager.
    spring.jta.narayana.recovery-jms-pass JMS password for recovery manager.
    spring.jta.narayana.recovery-jms-user JMS username for recovery manager.
    spring.jta.narayana.recovery-modules Comma-separated recovery modules.
    spring.jta.narayana.transaction-manager-id1Unique transaction manager id.
    spring.jta.narayana.xa-resource-orphan-filters Comma-separated orphan filters.

    By default, Narayana transaction logs written location is  transaction-logs directory in your application home directory (the directory in which your application jar file resides). You can customize the location of this directory by setting the narayana.log-dir or spring.jta.log-dir similar to that you can also customize the other properties.

    References

    Happy Learning !!!

    Springboot Framework Exception Hierarchy

    Springboot framework having following exceptions. These Spring exceptions occurred while developing applications.

    Springboot Framework Exception Hierarchy

    References

    https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/NestedRuntimeException.html

    Top [70] HR & Manager Round Interview Questions

    HR & Managerial round interview questions can cover a diverse range of discussion topics apart from Technical. These questions asked generally asked by laterals or experienced persons to check his/her personality/behaviour. In some organizations, this is also called a behaviour round of interviews. Generally, the interviewer observes these areas from your answers:

    1. Observe your expressions
    2. Check your leadership skills/soft skills
    3. Team handling skills
    4. Fit for organization cuture or not
    5. Client handling skills
    6. Handling on critical, stressed and pressurise work environment.
    How to introduce yourself

    The interviewer can create different scenarios for organization culture, team conflicts situation and some cases ask for combination with technology-related questions. Based on answered will ask for further questions. In such type questions, the interviewer wants to understand how you cope with change, approach learning, and overcome challenges and obstacles.

    In this article, we share some behaviour round interview questions with sample answers and also provide an overview of some additional example questions to prepare with a scenario that will fit your profile.

    Do you have any questions?

    How to answer to such behaviour and situational quetions?

    To prepare for these questions, take a moment to think of a number of challenging situations you have faced, such as difficulty with new technology, project, timeline, customer, ambiguity, process, or even a team member. Think of situations where you were challenged with what was the right thing to do. What did you do and how did you handle it? and how you can fit your previous experiences with current organization requirements.

    Always keep in mind the STAR rule to answer such behavioural questions.

    • S – Situation. What was the situation? Describe in brief. (This is the challenge you were facing.)
    • T – Task. What was the task you were assigned? What was your responsibility?
    • A – Action. What action did you take?
    • R – Result. What happened because of your action?

    You can use examples for reference and resolution you provided on a particular case.

    What are your strengths?

    Some of most frequently asked questions in behavioural interview

    Common Interview Questions

    These are common interview questions that can be asked in technical as well as in behavioural/manager/HR rounds of interviews. Through these questions, the interviewer wants to check your communication, understanding of your educational and professional background
    and your core technical skills instead of going through the complete CV.

    1. Tell Me About Yourself. Example
    2. Do you have any questions for us? Example
    3. What is your technical streagths and rate yourself in out of 10 points? Example
    4. Tell us about your educational and technical background. Example

    Behavioural Questions


    These questions are to check your personality, how you are socially connected, motivated and performed as an individual as part of the team so that interviewer can understand your compatibility with your current position requirement.

    1. How might you describe yourself? Example
    2. How might your friends describe you? Example
    3. What is your work ethic like? Example
    4. What are your strengths and weaknesses? Example
    5. Where Do You See Yourself In 5 Years? Example
    6. Why do you believe you are a good fit for this position? Example
    7. What is your idea of a friendly work environment? Example
    8. How do you react to sudden changes in the work you are doing? Example
    9. Share with us reasons you think we should hire you. Example
    10. If you could work in any position, what job might you want and why? Example
    11. Where did you learn about this open position? Example
    12. Have you ever worked in a leadership position? Example
    13. Share with us how you have emerged as a leader in the past. Example
    14. Talk to us about your skills, and how you believe they can help you excel in this position. Example
    15. How do you intend to continue expanding your professional skills? Example
    16. What roles have you previously worked in? Example
    17. What companies have you previously worked for? Example
    18. Do you have any references from previous experiences that we can contact? Example
    19. Explain the duties you have handled in the past. Example
    20. Have you ever received recognition for being a leader? Example
    21. How do you introduce new ideas or operations to teams? Example
    22. Why are you interested in leaving your current job? Example
    23. What feedback have previous managers given you about your work? Example
    24. How do you prioritise your tasks? Example
    25. Can you explain this gap in your resume? Example
    26. What are your salary expectations? Example
    27. Why Do You Want to Work Here? Example
    28. Why Should We Hire You? Example
    29. What Are Your Career Goals? Example
    30. What Is Your Greatest Accomplishment? Example

    Situational Questions


    These questions generally asked for lateral roles as lead or manager where you need to handle team or more on interacting with clients.

    1. What process might you use to make presentations for clients? Example
    2. Have you faced any hard time with client? Example
    3. What is your greatest professional accomplishment? Example
    4. Have you faced any critism from client or coworker? if yes, how you handled it? Example
    5. Have you faced any conflict with team or your manager? How did you deal with it? Example
    6. Have you resolved any conflict between team members? How did you deal with it? Example
    7. How do you handle workplace pressures? Example or
    8. Tell me about a time when you were under a lot of pressure. How did you handle it? Example
    9. Tell me about a time when you faced conflict at work. Example
    10. What is your greatest achievement? Example
    11. Tell me about a time you went above and beyond for work. Example
    12. Give me an example of a time you made a mistake. How did you manage the consequences? Example
    13. How would you respond to a request for doing a task you’ve never done before? Example
    14. Did you ever have to collaborate with a difficult coworker? How did you manage the situation? Example
    15. Tell me about a time when you handled a challenging situation. Example
    16. Was there a time when you were overwhelmed with work? How did you handle the situation? Example
    17. Sometimes almost impossible todo what are the things in our todo list. What you will do when your list of responsibilities overwhelming. Example
    18. Tell me a situation where you took the initiative to fix a problem. Example
    19. Tell me about a time when you and the team you were managing had opposing views on an issue. How did you get to a conclusion? Example
    20. How you accomplish task when there is tight deadline. Example
    21. Describe a long term project you managed. How did you make sure everything was running smoothly. Example
    22. Tell me about a time you had to deal with a client that was asking the impossible. Example
    23. Was there a time when you had to be very strategic in order to meet a goal?
    24. Give me an example of a situation when you showed initiative and took charge of a situation.
    25. Tell me about a time when you went above and beyond your duties for a job or task.
    26. Did you ever have to correct one of your superiors when they were wrong? How did you approach that situation?
    27. Have you ever had to work under a tight deadline?
    28. How do you deal with coworkers that don’t cooperate or can’t contribute enough?
    29. Tell me about a time when a client was asking for the impossible. How did you explain and communicate this to them?
    30. Give me an example of a time when you didn’t meet a client’s expectations. How did you deal with the situation?
    31. Is there a situation you think you could’ve handled better or differently?
    32. How do you adapt to sudden changes in the workplace? Could you give me an example? Example
    33. Tell me about a time when you had to think on your feet in order to deal with a situation.
    34. Sometimes employers put too much on their employees’ plates. Was there a time when you were overwhelmed with work? How did you handle the situation?
    35. Tell me about a time when you had the liberty to be creative with your work. Was it exciting or difficult for you?

    You can go through these questions to prepare any interview with your scenarios that best fit your roles and responsibility.

    Share your thoughts about these questions and also share if you faced any other questions to help others.

    Happy Learning !!!

    Spring Boot : Set JVM Parameters for an Application

    In Spring Boot application, you can set the JVM parameters by two ways so that increase the JVM heap size, in case required you can also configure the other parameters like GC alogorithms, MetaSpace etc.

    • Configure Parameters in pom.xml: To pass the JVM parameters for an application , we can set these parameters in spring-boot-maven-plugin in pom.xml plugin section.
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <jvmArguments>-Xms512m -Xmx1024m -XX:+UseZGC -XX:MaxMetaspaceSize=512m</jvmArguments>
        </configuration>
    </plugin>
    
    • Pass JVM parameters through Command line: We can pass the JVM parameters through the command line while running the Spring Boot application jar file.
    java -jar zyz-service.jar -Dspring-boot.run.jvmArguments="-Xms512m -Xmx1024m -XX:+UseZGC -XX:MaxMetaspaceSize=512m"
    

    Note: In both the cases these parameters are as below :

    • -Xms512m : Minimum heap size allocate for JVM as 512 MB.
    • -Xmx1024m : Max heap size can be allocate for JVM as 1024 MB.
    • -XX:+UseZGC : Garbage collection algorithm as Z Garbage Collector.
    • -XX:MaxMetaspaceSize=512m : By default in Java 8 or after the MetaSpace size is unlimited but we can configure fix Max limit also.

    Let me know the your thought on this post. If this was helpful for make a comment.

    Happy Learning !!!

    “Learn From Others Experience"

    %d bloggers like this: