Category Archives: Java

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] 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 !!!

    [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 !!!

    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 !!!

    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 !!!

    [Solved] OpenShift : MetaSpace Issue with SpringBoot based Micro-services

    The java.lang.OutOfMemoryError: Metaspace indicates that allocated native memory for Java class metadata is exausted. That’s why issue occured in standalone and cloud based applications.

    In Java 8 and later versions, the maximum amount of memory allocated for Java classes (MaxMetaspaceSize) is by default unlimited, so in most cases there is no need to change this setting. On the other hand, if you want to fix the amount of memory allocated for Java classes, you can set it as follows:

    java -XX:MaxMetaspaceSize=1024m
    

    This JVM parameter -XX:MaxMetaspaceSize is just an set the upper limit of MetaSpace. The current Metaspace size (i.e. committed) will be smaller. In fact, there is a setting called MaxMetaspaceFreeRatio (default 70%) which means that the actual metaspace size will never exceed 230% of its occupancy.

    And for it to grow it first would have to fill up, forcing a garbage collection in an attempt to free objects and only when it cannot meet its MinMetaspaceFreeRatio (default 40%) goal it would expand the current metaspace. That can however not be greater than 230% of the occupancy after the GC cycle.

    Monitoring MetaSpace Size with Java Native Memory tracking

    A good way to monitor the exact amount of Metadata is by using the NativeMemoryTracking, which can be added through the following settings:

    -XX:+UnlockDiagnosticVMOptions -XX:NativeMemoryTracking=detail -XX:+PrintNMTStatistics
    

    When Native Memory Tracking is enabled, you can request a report on the JVM memory usage using the following command:

    $ jcmd <pid> VM.native_memory
    

    OutOfMemoryError: Metaspace on OpenShift/Kubernetes

    When using openjdk Image on OpenShift/Kubernetes, the default maxium value for the Metaspace is XX:MaxMetaspaceSize=100m. You might have noticed that setting this value through the JAVA_OPTIONS environment variable, doesn’t work as the default value is appended to the bottom:

    VM Arguments: -Xms128m -Xmx1024m -XX:MetaspaceSize=128M -XX:MaxMetaspaceSize=256m    -XX:AdaptiveSizePolicyWeight=90 -XX:MaxMetaspaceSize=100m -XX:+ExitOnOutOfMemoryError
    

    Once the MetaSpace get full in your application it will stop the service and through exception as below in your logs.

    oc logs XYZ-service-7b856cc89-kpc6k  | grep -i metaspace
    INFO exec  java -javaagent:/usr/share/java/jolokia-jvm-agent/jolokia-jvm.jar=config=/opt/jboss/container/jolokia/etc/jolokia.properties -XX:+UseParallelOldGC -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=20 -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -XX:MaxMetaspaceSize=100m -XX:+ExitOnOutOfMemoryError -cp "." -jar /deployments/XYZ-service-0.0.1-SNAPSHOT.jar
    Picked up JAVA_TOOL_OPTIONS:  -Dappdynamics.agent.accountAccessKey=600a90af-582a-4ae2-87b1-4599708b65dd -Dappdynamics.agent.reuse.nodeName=true -Dappdynamics.socket.collection.bci.enable=true -XX:MaxMetaspaceSize=1024m -javaagent:/opt/appdynamics-java/javaagent.jar
    Terminating due to java.lang.OutOfMemoryError: Metaspace
    

    Solutions

    The correct way to set the MaxMetaspaceSize is through the GC_MAX_METASPACE_SIZE environment variable. Here are the different cases ti implement this solutions:

    • Jenkins Pipeline: For example, if you are using a jenkins pipeline to deploy your application or services then you can meke following changes in the json template to refelect these changes in deployment.yaml file to deploy your application with JKube, the following settings will override the default values for the MaxMetaspaceSize and MaxMetaspaceSize:
    spec:
      template:
        spec:
          containers:
          - env:
            - name: JAVA_OPTIONS
              value: '-Xms256m -Xmx1024m'
            - name: GC_MAX_METASPACE_SIZE
              value: 1024
            - name: GC_METASPACE_SIZE
              value: 256
    
    • Manual Deployment through S2I: You can directly pass these MetaSpace parameters while deploying your service manually.
    oc new-app xyz-service -e JAVA_OPTIONS="-Xms256m -Xmx1024m" -e GC_MAX_METASPACE_SIZE=1024 -e GC_METASPACE_SIZE=256
    

    Note : After deploying your service over OpenShift/Kernates validate the deployment configuration file(deployment.yml) for these parameters. In case not not reflecting then delete your pods completly and reploy the application.

    In case, you want make changes on other parameters also for improving the puformance of your applictaion then you can follow these documents to list of parameters for OpenShift.

    Let me know your thought on this post. if this solution was helpful for you make comment on the post.

    Happy Learning !!!

    Python: Nested Loop

    A loop within a loop is known as nested loop.

    Assume that there are 5 passengers and each of them have 2 baggage. The below code will make sure that all baggage of each passenger have undergone the security check.

    Example

    num_of_pasngrs=5
    num_of_bag=2
    security_check=True
    for pasngr_count in range(1, num_of_pasngrs+1):
    	  for bag_count in range(1,num_of_bag+1):
    	      if(security_check==True):
    	          print("Security check of passenger:", pasngr_count, "-- baggage:", bag_count,"baggage cleared")
    	      else:
    	          print("Security check of passenger:", pasngr_count, "-- baggage:", bag_count,"baggage not cleared")
    
    

    Output

    Security check of passenger: 1 — baggage: 1 baggage cleared
    Security check of passenger: 1 — baggage: 2 baggage cleared
    Security check of passenger: 2 — baggage: 1 baggage cleared
    Security check of passenger: 2 — baggage: 2 baggage cleared
    Security check of passenger: 3 — baggage: 1 baggage cleared
    Security check of passenger: 3 — baggage: 2 baggage cleared
    Security check of passenger: 4 — baggage: 1 baggage cleared
    Security check of passenger: 4 — baggage: 2 baggage cleared
    Security check of passenger: 5 — baggage: 1 baggage cleared
    Security check of passenger: 5 — baggage: 2 baggage cleared

    The same code in the inner loop can also be written using while loop instead of for loop as shown below:

    num_of_pasngrs=5
    num_of_bag=2
    security_check=True
    for pasngr_count in range(1, number_of_passengers+1):
    	bag_count =1
    	while (bag_count<=num_of_bag):
    	   if(security_check==True):
    	      print("Security check of passenger:", pasngr_count, "-- baggage:", bag_count,"baggage cleared")
    	   else:
    	      print("Security check of passenger:", pasngr_count, "-- baggage:", bag_count,"baggage not cleared")
    	   bag_count+=1	 
    
    

    Similarly, the outer loop can also be written using while loop.

    Java : Array & Arrays Class

    In this post we will discuss about Java Array and Arrays class to deal with array and perform different operation by  API’s.  Initially will discuss about Array for understanding and once you will get knowledge of Array then end of this post will discuss about Arrays API’s with examples.

    “Array is collection (or group of) of homogeneous (same data type) items  referred to single variable, which store in contiguous space in memory.”

    Note : Java works differently then they do in C/C++, In Java array elements are not stored in continuous locations.

    For example: You have 10 integer numbers and want minimum, maximum and  average of these numbers. One way is take 10 variables and perform comparison and operations of these numbers. If numbers are in hundreds very difficult to deal with that because need to handle 100 variables. That’s what array come on picture to deal with same type data.

    See Also: Java: Arrays vs Collections

    Points to remember:

    • Array always keep elements of same type such as primitive type or objects.
    • Array in Java array is dynamically allocated.
    • Array size always specified in int value not in short or long.
    • If number of elements in array are n ,then indexing of array start from 0…n-1.
    • Array is object in Java , if need to find  length, check for member length. To check length of array in C/C++ use sizeof.
    • Array can be use as static field, a local variable or a method parameter.
    • In java direct super class of Array is Object and implements java.lang.Cloneable and java.io.Serializable interface.
    • Time Complexity Access : Θ(1)
    • Time Complexity Search : Θ(n)
    • Time Complexity Insertion : Θ(n)
    • Time Complexity Deletion : Θ(n)
    • Space Complexity: O(n)

    In data structure array are two types:

    • One dimensional arrays
    • Multi dimensional arrays

    One Dimensional Array

    One dimensional array also called as linear array.

    Single Dimentional Array

    Declaration of Array

    Declaration show the reference of values as array and each value in array specified as type.

    type var-name [];
    or
    type [] var-name;
    

    Example to declare array of different types.

    // both are valid way of declarations
    int numbers[];
    or int[] numbers; 
    
    byte byteArr[];
    short shortsArr[];
    boolean booleanArr[];
    long longArr[];
    float floatArr[];
    double doubleArr[];
    char charArr[];
    //array of reference objects of Class Type MyTestClass
    MyTestClass myClassArray[]; 
    
    //Array of unknown type object, as oBject is super class of class class
    Object[]  objectArr,
    //Array of unknown type of collection as Collection is super interface in Collection framework
    Collection[] callectionArr;
    

    Instantiation of Array

    On array declaration only the reference of array created, to allocate memory to array need specified the size of array as below. where the size is always a integer value greater than zero.

    
    var-name = new type[size];
    

    For Example:

    int numbers[]; //declaration
    numbers=new int [10];//create an instance of array of 10 numbers.
    
    Object[] objectArr; //declaration
    
    objectArr=new Object[10]; //create an instance of array of 10 Objects.
    
    

    Note:

    • For primitive type array instantiation, array elements values by default initialize with specified primitive default value. For example : primitive type int default value is 0, all the  elements array by default initialize with 0.
    • For reference type array instantiation, array element values by default initialize with specified primitive default value. For example : reference type Object default value is null, all the  elements array by default initialize with null.

    Array Instantiation with Literals

    If you already know the elements of an array , use literals in array to instantiation and assignment of values at same time.

    //Array with int literals
    int [] numbers={10,, 50, 70 , 90, 80};
    //Array with String literals
    String [] names= {"Saurabh", "Gaurav", "Raghav"};
    

    Accessing of array

    To access/assign the elements of an array, use index position within range 0 to n-1 for the size of array length n. If trying to access array beyond this range (0…n-1) for primitive and reference type, get an exception as ArrayIndexOutOfBoundException in case of String will throw StringIndexOutOfBoundsException

    //accessing/assign value on array
    arrName[index];

    Example

    //access value from array on index position 2, will result 70
    int number=numbers[2];
    
    //Assign value on index position , new change value 80
    numbers[2]=80;
    

    Java Program for Single Dimensional Array

    Here is example of single line array , considering all above cases;

    
    public class OneDimentionalArray {
    
    	public static void main(String[] args) {
    
    		//declaration by both ways
    		int numbers[];
    
    		//Instantion for array of int type size 10
    		//By default initialize with 0 for primitive type int
    		numbers=new int[10];
    
    		//instantition with literals
    		String []names= {"Saurabh","Gaurav","Raghav"};
    
    		System.out.println("Print Numbers :");
    		//access array with for loop
            for(int i=0; i&lt;=numbers.length-1;i++)
    		{
    			System.out.println(numbers[i]);
    		}
    
    		System.out.println(&quot;\nPrint Name :&quot;);
    		//access array with for each loop
    		for(String name:names)
    		{
    			System.out.println(name);
    		}
    
    		// Assign values to Arrays by for loop
    		for(int i=0; i&lt;=numbers.length-1;i++)
    		{
    			numbers[i]=i*10;
    		}
    
    		//manually assign values,Raghav will replace with Ramesh
    		names[2]=&quot;Ramesh&quot;;
    
    		System.out.println(&quot;\n\nUpdate Values from arrays&quot;);
    
    		//access array with for loop
                    for(int i=0; i&lt;=numbers.length-1;i++)
    		{
    			System.out.println(numbers[i]);
    		}
    
    		System.out.println(&quot;\nPrint Name :&quot;);
    		//access array with for each loop
    		for(String name:names)
    		{
    			System.out.println(name);
    		}
    
    	}
    
    }
    
    

    Output

    Print Numbers :
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    
    Print Name :
    Saurabh
    Gaurav
    Raghav
    
    Update Values from arrays
    0
    10
    20
    30
    40
    50
    60
    70
    80
    90
    
    Print Name :
    Saurabh
    Gaurav
    Ramesh

    Multi Dimensional Array

    Multi-dimensional arrays also called Jagged Arrays, are arrays of arrays with each element of the array holding the reference of another array. A multi-dimensional array is created by appending square brackets ([]) per dimension.
    For Example

    int[][] intArr=new int [2][3]; //2D array
    int numbers[][][]=new int [2][3][4]; //3D array
    
    //2D representation with literals
    //Create an array of size [2][3] and assign given values
    int [][]numbers ={{2,5,7},{4,6,9}}

    Two Dimentional Array

    Java Program for Two Dimensional Array

    
    public class TwoDimentionalArray1 {
    
    	public static void main(String[] args) {
    
    		//declaration
    		int numbers[][] = {{2,5,7},{4,6,9}};
    
    		//access in array of two dimensional array
            for(int i=0; i&lt;=numbers.length-1;i++)
    		{
            	for (int j=0; j&lt;numbers[i].length;j++)
    			System.out.println(&quot;numbers[&quot;+i+&quot;][&quot;+j+&quot;]=&quot;+numbers[i][j]);
    		}
    
    		System.out.println(&quot;\n\nUpdate Values from arrays&quot;);
    
    		numbers[0][1]=20;
    		numbers[1][2]=30;
    		numbers[0][0]=40;
    
    		for(int i=0; i&lt;=numbers.length-1;i++)
    		{
            	for (int j=0; j&lt;numbers[i].length;j++)
    			System.out.println(&quot;numbers[&quot;+i+&quot;][&quot;+j+&quot;]=&quot;+numbers[i][j]);
    		}
    	}
    
    }
    

    Output

    numbers[0][0]=2
    numbers[0][1]=5
    numbers[0][2]=7
    numbers[1][0]=4
    numbers[1][1]=6
    numbers[1][2]=9
    
    Update Values from arrays
    numbers[0][0]=40
    numbers[0][1]=20
    numbers[0][2]=7
    numbers[1][0]=4
    numbers[1][1]=6
    numbers[1][2]=30

     

    Maven Vs Gradle

    Gradle is a built tool developed over Maven and Ant. It’s having lots of differences when compared with Maven.

    See Also:

    Maven Gradle
    Maven uses XML Gradle doesn’t use XML
    Maven written in Java Gradle written in Java, Kotlin and Gradle
    Maven scripts are not shorter and clean Gradle Scripts are shorter and clean
    Maven is a software project management and builds tool developed for Java-based applications. Gradle is an open-source, build automation system built on concepts of maven and ant.
    Maven makes build process easier, provides best guidelines for development and allow to migrate new features Gradle allows structuring of build and supports for multi projects builds. Gradle increases productivity provides ways to migrate and builds applications.

    Maven Vs Ant

    Ant was the first “modern” java application build tool released in 2000. It was famous in a short time because easy to learn, based on procedural programming and not required any additional preparation.

    Ant was having some issues in terms of, build time, performance and big scripts and other problems of developers.

    Maven releases in 2004 which covers all the problems of Ant and having a complete life cycle.

    See Also:

    Maven vs Ant

    Here are some main differences between Maven and Ant build tool.

    Ant Maven
    Ant required build script per project. Maven describes the project over configuration.
    Ant invoke project-specific targets Maven invoke defined goals (target)
    Ant is for “just” build process Maven required knowledge of the project.
    Ant scripts are too complex. Maven creates standard project layout and builds in the lifecycle.
    Ant scripts are not reusable. Maven plugins and repository are reusable.

     

    [Solved] TESSDATA_PREFIX environment variable is set to the parent directory of your “tessdata” directory.

    This exception happen when you trying to read text of image by using tessdata API’s. It try to get defalt path of environment variable TESSDATA_PREFIX in you application root diectory/tessdata/lang.traineddata. but if this folder and file not found then throw below exception.

    Stacktrace

    
    Exception in thread "main" java.lang.Error: Invalid memory access
        at com.sun.jna.Native.invokePointer(Native Method)
        at com.sun.jna.Function.invokePointer(Function.java:470)
        at com.sun.jna.Function.invoke(Function.java:404)
        at com.sun.jna.Function.invoke(Function.java:315)
        at com.sun.jna.Library$Handler.invoke(Library.java:212)
        at com.sun.proxy.$Proxy0.TessBaseAPIGetUTF8Text(Unknown Source)
        at net.sourceforge.tess4j.Tesseract.getOCRText(Tesseract.java:437)
        at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:292)
        at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:213)
        at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:197)
        at com.fiot.ImageTextReading.crackImage(ImageTextReading.java:22)
        at com.fiot.ImageTextReading.main(ImageTextReading.java:10)
        
    Error opening data file ./tessdata/eng.traineddata
    Please make sure the TESSDATA_PREFIX environment variable is set to the parent directory of your "tessdata" directory.
    Failed loading language 'eng'
    Tesseract couldn't load any languages!
        
    

    Solutions

    Follow these steps to resolve this issue:

    1. First download tessdata from this location https://github.com/tesseract-ocr/tessdata .
    2. Rename this unzip folder to tessdata.
    3. Copy this folder and paste it to your applciation root directory.

    For all steps and environment setup follow this example: Java : Read Text from and Image Example

    [Solved] java.lang.IllegalStateException: Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the class path

    This IllegalStateException for these jar conflict happens when you choose library in you class path that are internally use log4j and slf4j.

    In theory, If you are using log4j for logging, you could simply exclude the log4j-over-slf4j.jar because by using log4j,hacking other code to route the log4j calls to slf4j can lead to recursion and hence the strict check is there.

    Stacktrace

    
    Exception in thread "main" java.lang.ExceptionInInitializerError
        at org.slf4j.impl.StaticLoggerBinder.(StaticLoggerBinder.java:72)
        at org.slf4j.impl.StaticLoggerBinder.(StaticLoggerBinder.java:45)
        at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
        at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
        at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)
        at net.sourceforge.tess4j.Tesseract.(Tesseract.java:76)
        at imageread.ImageTextReading.crackImage(ImageTextReading.java:17)
        at imageread.ImageTextReading.main(ImageTextReading.java:9)
    Caused by: java.lang.IllegalStateException: Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the class path, preempting StackOverflowError. See also http://www.slf4j.org/codes.html#log4jDelegationLoop for more details.
        at org.slf4j.impl.Log4jLoggerFactory.(Log4jLoggerFactory.java:54)
        ... 9 more
    

    Solutions

    From your class path or pom.xml exclude dependencies for log4j and slf4j as below.

    In case of maven

    
    <exclusions>
      <exclusion> 
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
      </exclusion>
      <exclusion> 
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
      </exclusion>
    </exclusions>
    

    Incase of Gradle

    
    compile('org.xxx:xxx:1.0-SNAPSHOT'){
        exclude module: 'log4j'
        exclude module: 'slf4j-log4j12'
    }
    

    Java: Read Text from an Image

    Java provides net.sourceforge.tess4j library to read and extract text from the image. It makes developer life easy for applications where image reading is required.

    Example of Reading/Extract Text from Image

    1.  In the hospital, If you have scanned your doctor given a prescription and then some hospitals maintain patient records based on detail. then in the next visit after so many days, if you forget to carry it and the doctor asked about the previous prescription then based on your mobile number, name or date can reprint your doctor prescribed detail.
    2. In Big Data where need to do some analysis based on the above cases can extract detail from images and show reports.

    How Text Reading from image works?

    In an image extracting text means finding out the text components and then extract the geometric shape components. These text components are extract with geometric components as well and the relationship between these components built up by flow lines between components. These extracted components are a form of metadata (XML format), stored in a knowledge base or shared with others.

    Environment Setup

    Download tessdata from below git directory and rename to tessdata. Place this folder to your application root directory as below.

    https://github.com/tesseract-ocr/tessdata

    Read Text from Image Directory

    Dependency

    Add below dependency in your you application pom.xml

    
        <dependency> 
            <groupId>net.sourceforge.tess4j</groupId> 
            <artifactId>tess4j</artifactId> 
            <version>3.2.1</version> 
        </dependency>
    

     

    Java Code to Read Text from Image

    In this example, you will see complete steps to read/extract text from an image.

    Sample Image

    test image

    Java Code

    In this below image you will see complete java lines of code to extract text from the image and output of sample image.

    Java Code to Read Text from Image

    [Solved] javax.naming.NameNotFoundException: MyXYZConnectionFactory not found

    javax.naming.NameNotFoundException: MyXYZQueueConnectionFactory not found error occurred when JNDI name trying to configured it not exist on provider or some mismatch with name.

    For Example:
    In this example, I was trying to get MyXYZQueueConnectionFactory while factory on provider JNDI name is given as MyQueueConnectionFactory.

    Stacktrace of Error

    
    Binding name:`java:comp/env/jms/QueueName `
    Binding name:`java:comp/env/jms/MyQueueConnectionFactory `
    JNDI lookup failed: javax.naming.NameNotFoundException: MyXYZQueueConnectionFactory not found
    Unbinding name:`java:comp/env/jms/QueueName `
    Unbinding name:`java:comp/env/jms/MyXYZQueueConnectionFactory `
    

    Solutions

    • Check for JNDI name and factory created on configured server.
    • Check name of JNDI and factory is same as you want to pint on server.

    [Solved] JMSInitialContext: Unable to get the internal JNDI context

    JMSInitialContext: “Unable to get the internal JNDI context” error occurs when the developer/ config person has incorrectly specified the client properties file.

    For Example: A developer might have used the windows syntax for path in a unix system environment. This error can also occurred when the correct path to the app.properties file is not correct.

    Solutions

    The developer/config person has to define the path to the config directory properly and defined JNDI should be available.

    Stacktrace of Error

    
    java -Djms.properties=%J2EE_HOME%\config\app.properties MyQueueSender MyFIOTQueue
    

    Queue name is MyFIOTQueue

    
    SEVERE JMSInitialContext: Unable to get internal JNDI context because:
    javax.naming.CommunicationException: Cannot connect to ORB [Root exception is
    org.omg.CORBA.COMM_FAILURE: minor code: 789479689 completed: No]
    This error can be rectified by the user setting the class path for the client application correctly.
    

    [Java] Print characters having prime frequencies in order of occurrence.

    Question : Print characters having prime frequencies in order of occurrence

    Given a string str containing only lowercase characters. The task is to print the characters having prime frequency in the order of their occurrence. Note that repeated elements with prime frequencies are printed as many times as they occur in order of their occurrence.

    Examples:

    • Input: str = “facingissuesonit”
      Output: facingissuesonit Frequency
      ‘f’ 1
      ‘a’ 1
      ‘c’ 1
      ‘i’ 3
      ‘n’ 2
      ‘g’ 1
      ‘s’ 3
      ‘u’ 1
      ‘e’ 1
      ‘o’ 1
      ‘t’ 1

      ‘i’, ‘n’ and ‘s’ are the only characters with prime frequencies.
      Output: insinsis

    • Input: str = “aeroplane”
      Output: aeae

    Algorithm

    • Step 1: Ask the user to input String
    • Step 2: Get count of each character occurrence and insert in character-based sorted map
    • Step 3: Remove Character those occurrences are not Prime
    • Step 4: Print Character in alphabetical order and reduce the count by one
    • Step 5: Remove an entry from the map if the count is zero
    • Step 6: Repeat step 4 and 5 until map get empty

    Java Program

     

    public class Program2 {
    
    public static void main(String[] args) {
    
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a text String: ");
    String inputStr = input.nextLine();
    System.out.println("Result :" + primePlacesString(inputStr));
    }
    
    private static List primePlacesString(String inputStr) {
    List charList = null;
    char[] chars = inputStr.toCharArray();
    // Enter Character and respected occurence in map
    TreeMap map = new TreeMap();
    for (Character c : chars) {
    if (map.get(c) == null) {
    map.put(c, 1);
    } else {
    map.put(c, map.get(c).intValue() + 1);
    }
    }
    // Removed character those occurence are not prime
    Character[] keys = (Character[]) map.keySet().toArray(new Character[map.size()]);
    for (Character key : keys) {
    if (!isPrimeNumber(map.get(key))) {
    map.remove(key);
    }
    }
    // get list of character in sequence as per counts
    if (map != null &amp;&amp; !map.isEmpty()) {
    charList = new ArrayList();
    printMapInSquence(map, charList);
    }
    return charList;
    }
    
    // Code to check number is prime or not
    private static boolean isPrimeNumber(Integer number) {
    boolean isPrimeNumber = true;
    if (number == 0 || number == 1) {
    isPrimeNumber = false;
    } else {
    for (int i = 2; i &lt;= number / 2; i++) {
    if (number % i == 0) {
    isPrimeNumber = false;
    break;
    }
    }
    }
    
    return isPrimeNumber;
    }
    
    private static void printMapInSquence(Map map, List charList) {
    if (map != null &amp;&amp; !map.isEmpty()) {
    
    Character[] keys = (Character[]) map.keySet().toArray(new Character[map.size()]);
    for (Character key : keys) {
    charList.add(key);
    if (map.get(key) == 1) {
    // remove characters those are already printed and count are 1
    map.remove(key);
    } else {
    // reduce counts of printed characters and counts more than one
    map.put(key, map.get(key) - 1);
    }
    }
    printMapInSquence(map, charList);
    }
    }
    
    }
    
    

    Output

    
    Enter a text String: facingissuesonit
    Result :[i, n, s, i, n, s, i, s]
    
    Enter a text String: aeroplane
    Result :[a, e, a, e]
    

    Java Program : Get all possible values of X such that A % X = B

    Question:  Write a java program to get  all possible values of X such that A % X = B. Input two integers A and B. The task is to find the  all possible values X such that A % X = B. If there are infinite number of possible values then print -1.

    Examples:

    1. Input: A = 21, B = 5
      Output: 2
      8 and 16 are the only valid values for X.
    2. Input: A = 5, B = 5
      Output: -1
      X can have any value > 5

    Algorithm

    • Step 1: Ask the user to input values of A and B
    • Step 2: Find out all possible factors of (A-B) which are greater than B
    • Step 3: Use StringJoiner to print the possible value in comma separated form.

    Java Program

    public class Program1 {
    public static void main(String[] args) {
    System.out.println("Enter values of A and B to get possible values of X from expression A % X = B");
    
    Scanner input = new Scanner(System.in);
    System.out.print("Please Enter an integer A: ");
    int A = input.nextInt();
    
    System.out.print("Please Enter an integer B: ");
    int B = input.nextInt();
    
    System.out.println("Possible Values of X :" + getAllowedValues(A, B));
    }
    
    private static String getAllowedValues(int A, int B) {
    //Use to print value in comma separated form
    StringJoiner joiner = new StringJoiner(",");
    
    if (A - B &gt; 0) {
    //find out all possible factor of(A-B) which are greater than B
    for (int C = (A - B); C &gt; 0 &amp; C &gt; B; C /= 2) {
    if ((A - B) % C == 0)
    joiner.add(Integer.toString(C));
    }
    } else {
    joiner.add("-1");
    }
    return joiner.toString();
    }
    
    }
    

    Output

    
    Enter values of A and B to get possible values of X from expression A % X = B
    Please Enter an integer A: 21
    Please Enter an integer B: 5
    Possible Values of X :16,8
    
    Enter values of A and B to get possible values of X from expression A % X = B
    Please Enter an integer A: 5
    Please Enter an integer B: 5
    Possible Values of X :-1
    
    

    [Solved] javax.crypto.AEADBadTagException: Tag mismatch

    AEADBadTagException is subclass of BadPaddingException. It’s occurred when a Cipher unable to verify the authentication tag. It’s occurred when Cipher is AEAD i.e GCM/CCM mode.

    public class AEADBadTagException extends BadPaddingException
    

    Constructor

    • AEADBadTagException(): Constructs a default constructor of AEADBadTagException with no detail message.
    • AEADBadTagException(String msg): Constructs a message constructor of AEADBadTagException with the specified detail message.

    Exception

    Here is a complete example of encryption and decryption based on algorithm AES/GCM/NoPadding but having an issue because of IV value which is used for authentication.

    import java.security.SecureRandom;
    import java.util.Base64;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.GCMParameterSpec;
    import javax.crypto.spec.SecretKeySpec;<span id="mce_SELREST_start" style="overflow:hidden;line-height:0"></span>
    /**
    * example for plain text encryption and decryption by using Java AES 256 GCM Encryption Algorithm
    */
    public class AES_GCM_Example
    {
    static String plainText = "facing Issues on IT  (Learn from Others Experience)";
    public static final int AES_KEY_SIZE = 256;
    public static final int GCM_IV_LENGTH = 12;
    public static final int GCM_TAG_LENGTH = 16;
    
    public static void main(String[] args) throws Exception
    {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(AES_KEY_SIZE);
    
    // Generate Key
    SecretKey key = keyGenerator.generateKey();
    
    byte[] IV = new byte[GCM_IV_LENGTH];
    SecureRandom random = new SecureRandom();
    random.nextBytes(IV);
    
    System.out.println("Original Text : " + plainText);
    
    byte[] cipherText = encrypt(plainText.getBytes(), key, IV);
    System.out.println("Encrypted Text : " + Base64.getEncoder().encodeToString(cipherText));
    
    String decryptedText = decrypt(cipherText, key, IV);
    System.out.println("DeCrypted Text : " + decryptedText);
    }
    
    public static byte[] encrypt(byte[] plaintext, SecretKey key, byte[] IV) throws Exception
    {
    // Get Cipher Instance for selected algorithm
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    
    // Create SecretKeySpec for key
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
    
    // Create GCMParameterSpec for key
    GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, IV);
    
    // Initialize Cipher for ENCRYPT_MODE for encrypt plaintext
    cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);
    
    // Perform Encryption
    byte[] cipherText = cipher.doFinal(plaintext);
    
    return cipherText;
    }
    
    public static String decrypt(byte[] cipherText, SecretKey key, byte[] IV) throws Exception
    {
    // Get Cipher Instance based on selective AES algorithm
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    
    // Create SecretKeySpec for key
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
    
    // Create GCMParameterSpec for key
    //IV = new byte[GCM_IV_LENGTH]; //here is issue
    
    GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, IV);
    
    // Initialize Cipher for DECRYPT_MODE to in plain text
    cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
    
    // Perform Decryption on encrypted text
    byte[] decryptedText = cipher.doFinal(cipherText);
    
    return new String(decryptedText);
    }
    
    }
    

    Output

    
    Original Text : facing Issues on IT  (Learn from Others Experience)
    Encrypted Text : AxboQXVKKPMm05cRaslMuxDl8IK77OLgG2ddnVSKzQUVQEXL/Xic+OHN/8ixbrFbvSrytStUWBsYQyXIWLQB22+0sg==
    Exception in thread "main" javax.crypto.AEADBadTagException: Tag mismatch!
           at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:524)
           at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1023)
           at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:960)
           at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
           at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
           at javax.crypto.Cipher.doFinal(Cipher.java:2121)
           at enc_dec.AES_GCM_Example.decrypt(AES_GCM_Example.java:84)
           at enc_dec.AES_GCM_Example.main(AES_GCM_Example.java:41)
    

    Solution

    Here is an issue on decryption while changing the value of IV as in line by creating new byte array which is different from the value passed in encryption that’s why encryption and decryption authentication get failed.

    As a solution specific this issue comment line 68 and it will return output as below.

    
    Original Text : facing Issues on IT  (Learn from Others Experience)
    Encrypted Text : faSkDrA737VyiocRk1n5arFGaO5r7GDN6xFmz7hjZppkN0y8sgcj9N5iqaZ2+gbRowli5Ocfm1sQB2qL+nEVIzsWVg==
    DeCrypted Text : facing Issues on IT  (Learn from Others Experience)
    

    References

    Apache Tika Introduction

    Apache Tika provides generic API for all document type content detection, analysis and content extraction from multiple file formats. Tika internally uses various documents parsers to extract metadata and structured text content from the various file types. For Example PDF, Spreadsheet, text file, images, etc.

    Tika latest version 1.22 released on 1st Aug 2019 by Apache software foundation. Tika completely has written in Java and supports cross-platform.

    Tika Version History

    Year Development
    2006 The idea of Tika was proposed in front of the Lucene Project Management Committee.
    2006 The concept of Tika and its benefits in the Jackrabbit project was discussed.
    2007 Tika entered into Apache.
    2008 Both 0.1 and 0.2 Versions were released and Tika graduated from the incubator to the Lucene sub-project.
    2009 This year Tika Versions 0.3, 0.4, and 0.5 were released.
    2010 Both 0.6 and 0.7 Version was released and Tika graduated into the top-level Apache project.
    2011 Tika 1.0 was released with book “Tika in Action” was also released in the same year.
    2019 Tika 1.22 was release for additional CSV and HWP files type.

    Why Tika?

    As per https://filext.com/, there are around 25k to 50K file extensions (Structured and Non Structured) and these are growing day by day. To deal with so many types of format Tika provides universal Java API to support around 1400 file types that cover most common and popular formats.

    Tika provides content extraction, metadata extraction, and language identification capabilities. Tika written in Java, still used by other languages also by calling restful services and CLI tools.

    Where to use Apache Tika?

    • Search Engine: Tika uses the search engine to create search indexing for text in digital documents.
    • Document Analysis: Analysis of the documents like images, pdf to do analysis based on extract content.
    • Digital Asset Management (DAM): It’s used with an organization where maintains a library of documents, images, videos, ebooks, drawings to classify based on common features.
    • Content Analysis: Analyse the content from the web site and care of user’s interest like amazon shows movies, products based on the user’s visit. Machine learning based on content.

    Features of Tika

    • Unified parser Interface: Tika internally uses best suitable parser libraries within a single parser interface. Due to this feature Tika, reduce the burden of developer from the burden of selecting the suitable parser library and use it according to the file type encountered.
    • Low memory usage: Tika consumes fewer memory resources, therefore, it is easily embedded with Java applications. We can also use Tika within the application which runs on platforms with fewer resources like mobile PDA.
    • Fast processing: Tika can quickly extract and detect content from applications.
    • Flexible metadata: Tika understands all type of metadata models which are used to define files.
    • Parser integration: Tika supports various parser libraries available for each document type in the same application.
    • MIME-type detection: Tika can extract and detect content from all MIME types.
    • Language detection: Tika includes language identification feature, therefore it can be used in documents based on language type in multilingual websites.

    Java: Collection Framework Introduction

    A collection is an object (also called container) to deal with a group of objects or elements as a single unit. These objects called as elements of Collection. Collections are used to perform operations like the store, retrieve, manipulate, communicate and aggregate.

    A collection can have a different type of data. Based on data can decide the type collection data structure.

    • Homogeneous
    • Heterogeneous
    • Unique
    • Duplicate

    See Also: 

    Real-life Example of Collection

    Here are some real-life examples of collections:

    • LinkedList: Your web page visiting history.
    • LinkedList: Train Coaches are connected to each other.
    • LinkedList: Our brain, when we remember something memory follow association because of one memory link to another.  This way recall in sequence.
    • Stack & LinkedList: Stack of Plates or Towel at the party. The top plate always picks first.
    • Queue & LinkedList: Queue/line of the person standing on the railway ticket window or for food in the mess.
    • A classroom is a collection of students.
    • A money bank is a collection of coins.
    • A school bag is a collection of books.

    Why need collection?

    There are four ways in Java to store values by JVM.

    1:Variable approach

    If we need to handle one, two or three or fewer numbers of values then the variable approach is a good bit if need to deal with so many objects like 5000 then variable approach have some drawback:

    • The limitation of a variable is that it can store only one value at a time.
    • Readability and reusability of the code will be down.
    • JVM will take more time for the execution.

    2: Using a class object approach

    Using a class object, we can store multiple “fixed” numbers of values of different types. For example, suppose we are creating a class named Person.

    class Person{
    String Name ;
    int age ;
    }
    

    If you create the object of Person class like this

    Person p1=new Person(); // So can you think how many values can store in this person object?
    

    The answer is only two i.e name and age. but if you will want to store the third value, it will not possible.

    3: Using an array object approach

    Array improved the readability of code, by using a single variable for a huge number of values but there are various problems and limitations with the array.

    
    Student[] st=new Student[5000];
    
    1. Array allow to store only homogeneous data type.
    2. Array is static and fixed in length size.
    3. Array concept help with standard data structure, but when need to deal with the sorting of objects, search for a specific item, etc.

    4: Collection Object:

    By using a collection object, we can store the same or different data without any size limitation.

    What is a Framework in Java?

    A framework is a set of several classes and interfaces which provide a readymade architecture.

    What is a Collections Framework?

    A collection framework provides a unified readymade architecture for storing and manipulating a group of objects. All collections frameworks contain the following:

    • Interfaces: Interfaces generally forms a hierarchy and allow collections object to be manipulated independently of the details of their representation.
    • Implementations: Provides a concrete representation by data structure and implementation of  collections interfaces.
    • Algorithms: The methods that perform useful operations, such as searching and sorting, on objects that implement collection interfaces.

    Benefits of Collections Framework

    Collections Framework provides lots of benefits:

    • Reduces programming effort: The Collections framework provides useful data structures and algorithms so that developers can concentrate on programming logic only.
    • Increases program performance and quality: Collections Framework provides high-quality data structures and algorithms implementations for good performance. These collections interface APIs are interchangeable so that easily tuned by switching collection implementations.
    • Allows interoperability among unrelated APIs: These data structures are interchangeable so that choose data structure and algorithms according to requirement.
    • Reduces effort to learn and to use new APIs: Most of APIs are common for collections framework because of the inherent Collection interface. only some APIs need to remember that are specific to the data structure.
    • Reduces effort to design new APIs: If new data structure and algorithm change create polymorphism of API and change the internal algorithm of APIs.
    • Fosters software reuse: If new data structure added use standard APIs so that easy to learn for developers.

    References

    Java : Collection Framework Hierarchy

    All the classes and interfaces of the collection framework are in java.util package. This hierarchy for the collection framework specifically mentioned the class and interface with respect to each type.

    Java Collection Framework Hierarchy

    Iterable Interface

    The Iterable interface is the root interface for all the collection classes because the Collection interface extends the Iterable interface, therefore, all the subclasses of Collection interface also implement the Iterable interface.

    The iterable interface contains only one abstract method.

    • Iterator iterator(): It returns the iterator over the elements of type T.

    Iterator Interface

    The iterator interface provides the facility of iterating the elements in a forward direction only.
    For more detail: Java: Iterator Interface methods and Examples

    Collection Interface

    The Collection interface builds the foundation for the Collection framework. The collection interface is one of the interfaces which is implemented by all the Collection framework classes. It provides common methods to implement by all the subclasses of collection interfaces.
    For more detail: Java: Collection Interface methods and Examples

    List Interface

    List interface is the subtype/child interface of the Collection interface. It stores objects/elements in list type data structure in ordered form and also allowed duplicate values.

    Implementation classes for List interface are ArrayList, LinkedList, Vector, and Stack.

    For Example: To instantiate List Interface with Implementation classes follow:

    
    List  list1= new ArrayList();  
    List  list2 = new LinkedList();  
    List  list3 = new Vector();  
    List  list4 = new Stack();
    

    For more detail: Java: List Interface methods and Examples

    ArrayList Class

    The ArrayList implements the List interface. It’s having the following features:

    • ArrayList uses a dynamic array data structure to store objects and elements.
    • ArrayList allows duplicate objects and elements.
    • ArrayList maintains the insertion order.
    • ArrayList is non-synchronized.
    • ArrayList elements/objects can be accessed randomly.

    For more detail: Java: ArrayList Interface methods and Examples

    LinkedList Class

    LinkedList implements the List interface. It’s having the following features:

    • LinkedList uses a doubly linked list data structure to store elements.
    • LinkedList allowed storing the duplicate elements.
    • LinkedList maintains the insertion order.
    • LinkedList is not synchronized.
    • LinkedList manipulation is fast because no shifting is required.

    For more detail: Java: LinkedList Class methods and Examples

    Vector Class

    Vector Class implements List interface. It’s having the following features:

    • Vector is similar to the ArrayList class.
    • Vector class uses data structure as a dynamic array to store the data elements.
    • Vector is synchronized.
    • Vector contains many methods that are not the part of Collection Framework.

    For more detail: Java: Vector Class methods and Examples

    Stack Class

    The Stack is the subclass of the Vector class. It’s having the following features:

    • Stack implements the Vector data structure with the (LIFO)last-in-first-out.
    • Stack contains all of the methods of the Vector class.
    • Stack also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its features.

    For more detail: Java: Stack Class methods and Examples

    Queue Interface

    Queue Interface extends the Collection interface. It’s having the following features:

    • Queue interface maintains the FIFO (first-in-first-out) order.
    • Queue can be defined as an ordered list that is used to hold the elements which are about to be processed.
    • Queue interface implemented by the various classes like PriorityQueue, Deque, and ArrayDeque.

    Queue interface can be instantiated as:

    Queue q1 = new PriorityQueue();  
    Queue q2 = new ArrayDeque();  
    

    For more detail: Java: Queue Interface methods and Examples

    Here are detail about classes which implements Queue Interface.

    PriorityQueue

    The PriorityQueue class implements the Queue interface.

    • PriorityQueue holds the elements or objects which are to be processed by their priorities.
      PriorityQueue doesn’t allow null values to be stored in the queue.

    For more detail: Java: PriorityQueue Class methods and Examples

    Deque Interface

    Deque stands for the double-ended queue which allows us to perform the operations at both ends.interface extends the Queue interface.

    • Deque extends the Queue interface.
    • Deque allows remove and add the elements from both the side.
    Deque d = new ArrayDeque(); 
    

    For more detail: Java: Deque Interface methods and Examples

    ArrayDeque Class

    ArrayDeque class implements the Deque interface.

    • ArrayDeque facilitates us to use the Deque.
    • ArrayDeque allows add or delete the elements from both the ends.
    • ArrayDeque is faster than ArrayList and has no capacity restrictions.

    For more detail: Java: ArrayQueue Class methods and Examples

    Set Interface

    Set Interface extends Collection Interface and present in java.util package.

    • Set doesn’t allow duplicate elements or objects.
    • Set store elements in an unordered way.
    • Set allows only one null value.
    • Set is implemented by HashSet, LinkedHashSet, and TreeSet.

    We can create an instantiation of Set as below:

    Set s1 = new HashSet();  
    Set s2 = new LinkedHashSet();  
    Set s3 = new TreeSet();
    

    For more detail: Java: Set Interface methods and Examples

    HashSet

    HashSet class implements Set Interface. It’s having the following features:

    • HashSet internally uses data structure like a hash table for storage.
    • HashSet uses hashing technique for storage of the elements.
    • HashSet always contains unique items.

    For more detail: Java: HashSet Class methods and Examples

    LinkedHashSet

    LinkedHashSet class implements Set Interface. It’s having the following features:

    • LinkedHashSet store items in LinkedList.
    • LinkedHashSet store unique elements.
    • LinkedHashSet maintains the insertion order.
    • LinkedHashSet allows null elements.

    For more detail: Java: LinkedHashSet Class methods and Examples

    SortedSet Interface

    SortedSet Interface extends Set Interface. It’s having the following features:

    • SortedSet provides a total ordering on its elements.
    • SortedSet elements are arranged in the increasing (ascending) order.
    • SortedSet provides additional methods that inhibit the natural ordering of the elements.

    The SortedSet can be instantiated as:

    SortedSet set = new TreeSet();  
    

    For more detail: Java: SortedSet Interface methods and Examples

    TreeSet Class

    TreeSet class implements the SortedSet interface.  It’s having the following features:

    • TreeSet uses a tree data structure for storage.
    • TreeSet also contains unique elements.
    • TreeSet elements access and retrieval time is quite fast.
    • TreeSet elements stored in ascending order.

    For more detail: Java: TreeSet Class methods and Examples

    Map Interface

    In the collection framework, a map contains values on the basis of key and value pair. This pair is known as an entry. A map having the following features:

    • Map contains unique keys.
    • Map allows duplicate values.
    • Map is useful to search, update or delete elements on the basis of a key.
    • Map is the root interface in Map hierarchy for Collection Framework.
    • Map interface is extended by SortedMap and implemented by HashMap, LinkedHashMap.
    • Map implementation classes HashMap and LinkedHashMap allow null keys and values but TreeMap doesn’t allow null key and value.
    • Map can’t be traversed, for traversing needs to convert into the set using method keySet() or entrySet().

    For more detail: Java: Map Class methods and Examples

    HashMap Class

    HashMap class implements Map interface. It’s having following features:

    • HashMap uses data structure as a Hash Table.
    • HashMap store values based on keys.
    • HashMap contains unique keys.
    • HashMap allows duplicate values.
    • HashMap doesn’t maintain order.
    • HashMap class allows only one null key and multiple null values.
    • HashMap is not synchronized.
    • HashMap initial default capacity is 16 elements with a load factor of 0.75.

    For more detail:

    LinkedHashMap Class

    LinkedHashMap class extends the HashMap class. It’s having the following features:

    • LinkedHashMap contains values based on the key.
    • LinkedHashMap contains unique elements.
    • LinkedHashMap may have one null key and multiple null values.
    • LinkedHashMap is not synchronized.
    • LinkedHashMap maintains the insertion order.
    • LinkedHashMap default initial capacity is 16 with a load factor of 0.75.

    For more detail: Java: LinkedHashMap Class methods and Examples

    TreeMap Class

    TreeMap class implements the SortedMap interface. it’s having the following features:

    • TreeMap uses data structure as red-black tree.
    • TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
    • TreeMap contains only unique elements.
    • TreeMap doesn’t allow null keys and values.
    • TreeMap is not synchronized.
    • TreeMap maintains an ascending order.

    For more detail: Java: TreeMap Class methods and Examples

    HashTable Class

    Hashtable class implements a Map interface and extends Dictionary class to store key and values as pairs. It’s having the following features:

    • HashTable store values as an array of the list where each list is known as a bucket of the node(key and value pair).
    • HashTable class is in java.util package.
    • Hashtable contains unique elements.
    • Hashtable doesn’t allow null key or value.
    • Hashtable is synchronized.
    • Hashtable initial default capacity is 11 whereas the load factor is 0.75.

    For more detail: Java: HashTable Class methods and Examples

    See Also:

    Java: HashCode and Equals Contract

    In Java java.lang.Object is the superclass of all the classes provides two very important methods :

    public boolean equals(Object obj)
    public int hashCode()
    

    See Also:

    Internally these methods are used when need to check equality of objects but developer implementation prospects mainly used when need to implement HashMap because on that time developers have to implement these methods inside your User Defined class. Lot’s of the time when the developer is not aware of the contract of hashcode() and equals() method they make mistake and not received expected results from HashMap. Before going to detail of hashcode() and equals() contract, Let’s discuss first the problems.

    Most Common Problem

    In this example,  green and red car object is stored successfully in a HashMap, but when the map is asked to retrieve this green car object, the car object is not found in map and returning as null.

    import java.util.HashMap;
    import java.util.Map;
    
    public class Car {
    	private String color;
    
    	public Car(String color) {
    		this.color = color;
    	}
    
    	public boolean equals(Object obj) {
    		if (!(obj instanceof Car))
    			return false;
    		if (obj == this)
    			return true;
    		return this.color.equals(((Car) obj).color);
    	}
    	public static void main(String[] args) {
    		Car a1 = new Car("green");//hashcode
    		Car a2 = new Car("red");
    
    		// HashMap stores car type and its quantity
    		Map m = new HashMap();
    		m.put(a1, 10);
    		m.put(a2, 20);
    		//hashcode diffrent from previos green object consider different object
    		System.out.println(m.get(new Car("green")));
    	}
    }
             

    Output

    null
    

    The above program prints as null. However, we can check that this car object is stored in the map by inspecting in the debugger:

    Java hashCode and Equals Contract

    In the above program problem is hashcode() method was not implemented.

    Before going to the solution to this problem in detail. We need to understand the equals() and hashcode() method contract.

    hashcode() and equals() Method Contract

    The contract between equals() and hasCode() is that:

    1.  If two objects are equal, then they must have the same hash code value.
    2.  If two objects have the same hashcode value, they may or may not be equal.

    The main idea is Map worked on hashing techniques to find an object faster in comparison to linear search. In this case, because the hashcode() method is no implemented. It will call by default method of object class i.e return different hashcode value for different objects. In this above case both the objects store in HashMap and retrieving will have different hashcode values.

    See Also: Java: Hashmap Working

    In HashMap, store values in form array of buckets of the object where these array having hashcode value while objects having objects that match with the same hashcode. For example, the Hash Code is like a sequence of boxes for storage where different kinds of stuff can be stored in different boxes. It is more efficient if you organize stuff to a different place instead of the same garage. So it’s a good practice to keep kinds of stuff on related boxes i.e equally distribute the hashCode value.

    The solution is to add hashCode() method to the Car class. Here we are getting hash value based on the size of color length as implemented below.

    import java.util.HashMap;
    import java.util.Map;
    
    public class Car {
    	private String color;
    
    	public Car(String color) {
    		this.color = color;
    	}
    
    	public boolean equals(Object obj) {
    		if (!(obj instanceof Car))
    			return false;
    		if (obj == this)
    			return true;
    		return this.color.equals(((Car) obj).color);
    	}
    
    	public int hashCode(){
    		return this.color.length();
    }
    	public static void main(String[] args) {
    		Car a1 = new Car("green");//hashcode
    		Car a2 = new Car("red");
    
    		// HashMap stores car type and its quantity
    		Map m = new HashMap();
    		m.put(a1, 10);
    		m.put(a2, 20);
    		//hashcode different from previous green object consider different object
    		System.out.println(m.get(new Car("green")));
    	}
    
    }
    

    Output

    10
    

    Java: Aggregation and Composition (HAS-A)

    Pre-requisite: Java: OOPS Concepts, Java: Class, Java: Object

    If objects are having an association as “HAS-A” then there could be two types of relationship between objects:

    1. Aggregation
    2. Composition

    Aggregation

    Aggregation is a special type of association where objects have their independent life cycle but there is ownership. These owners and associate objects have the “HAS-A” relationship.

    For Example, A person may associate with an Organization but he/she has an independent existence in the world.

    Benefits of Aggregation

    • Aggregation provides reusability.

    Note: For code reusability, if classes having IS-A relationship use Inheritance and for Has-A relationship use Aggregation.

    Example of Aggregation

    Here Employee class is associated with address class with Aggregation (HAS-A) relationship. Employee class contained an object of Address, this address object contains its own information like city, state, country, etc. Both of these objects are not strongly associate because if employee looses their jobs but still have the same address.

    public class Address {
    	String city, state, country;
    
    	public Address(String city, String state, String country) {
    		this.city = city;
    		this.state = state;
    		this.country = country;
    	}
    
    }
    

     

     

    public class Employee {
    	int id;
    	String name;
    	Address address;
    
    	public Employee(int id, String name, Address address) {
    		this.id = id;
    		this.name = name;
    		this.address = address;
    	}
    
    	void display() {
    		System.out.println(id + " " + name);
    		System.out.println(address.city + " " + address.state + " " + address.country);
    	}
    
    	public static void main(String[] args) {
    		Address address1 = new Address("Noida", "UP", "India");
    		Address address2 = new Address("Greater Noida", "UP", "India");
    
    		Employee e = new Employee(101, "Saurabh", address1);
    		Employee e2 = new Employee(102, "Gaurav", address2);
    
    		e.display();
    		e2.display();
    
    	}
    }
    

    Composition

    The composition is special type of aggregation where one object is strongly associated with another object and more restrictive. When the contained object in “HAS-A” and one object can not exist without the existence of others it’s the case of composition.

    For Example:

    • Wheels in a car.
    • House has a room. Here the room can’t exist without the house.
    • An employee has a job. A job can’t exist without an employee.

    Benefits of Composition

    • The composition provides reusability.
    • The composition can control the visibility of another object and reuse only when needed.

    Examples of Compositions
    Here Person and Job class having a composition relationship. In this case, Job class creates at runtime whenever a new person comes and we can change the salary from backend without change on client-side.

    public class Person {
    	//composition has-a relationship
        private Job job;
    
        public Person(){
            this.job=new Job();
            job.setSalary(1000L);
        }
        public long getSalary() {
            return job.getSalary();
        }
    }
    
    public class Job {
    	private String role;
        private long salary;
        private int id;
    
        public String getRole() {
            return role;
        }
        public void setRole(String role) {
            this.role = role;
        }
        public long getSalary() {
            return salary;
        }
        public void setSalary(long salary) {
            this.salary = salary;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
    
    }
    
    public class TestComposition {
    
    	public static void main(String[] args) {
    		Person person = new Person();
    		long salary = person.getSalary();
    
    	}
    
    }
    

    Examples of Compositions & Aggregation
    Let’s have an example of a University, it’s department and professors associated with departments.

    University & Department Association: It’s a composition association because without University will exist in any department.
    Department and Professors Association: It’s aggregate association because both are associated but not having any dependency like if department close professor lose. Both are are an independent entities.

    import java.util.List;
    
    public class University {
    	 private List departments;
    
         public void destroy(){
             //it's composition, when i destroy a university I also
    		 //destroy the departments. they cant live without university instance
             if(departments!=null)
                 for(Department d : departments) d.destroy();
             departments.clear();
             departments = null;
         }
    
    }
    
    public class Department {
    	private List professors;
        private University university;
    
        Department(University univ){
            this.university = univ;
            //check here univ not null throw whatever depending on your needs
        }
    
        public void destroy(){
            //It's aggregation here, if we fire any professor then they
    		//will come out of department but they can still keep living
            for(Professor p:professors)
                p.fire(this);
            professors.clear();
            professors = null;
        }
    
    }
    
    public class Professor {
    	 private String name;
         private List attachedDepartments;
    
         public void destroy(){
    
         }
    
         public void fire(Department d){
             attachedDepartments.remove(d);
         }
    }
    

    Java: Inheritance (IS-A)

    Pre-requisite: Java: OOPS Concepts, Java: Class, Java: Object

    Inheritance is a process where child class acquired all the properties and behaviors of the parent class. Inheritance is used when one object is based on another object. Here parent class also called a superclass and child class called a subclass.

    For Example,  Person is Parent class and Employee is a subclass of Person. which acquired all the properties and behavior of Person class.

    Advantage of inheritance

    What is code Reusability in Inheritance?

    Inheritance facilitates to reuse the fields and methods of the parent class in child class syntax of Java Inheritance.

    Syntax of Inheritance Declaration

    class Subclass-name extends Superclass-name  
    {  
       //fields 
       //methods   
    }

    In java, extends keyword is used to inherit a class where a new class derived properties and methods of an existing class. The class that inherited is called a Parent/Superclass, and a new derived class is called a child/subclass.

    What You Can Do in a Subclass?

    A subclass inherits all of the public and protected members(fields, methods and nested classes) of its parent class, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the private members of the parent class.

    Constructors are not members of the class, so they are not inherited by child class, but the constructor of the parent class can be invoked from the child class by using super.

    These inherited members can use as-is, replace them, hide them, or supplement them with new members:

    • Parent class inherited fields  can be used directly, just like any other class field.
    • You can declare a field in the child class with the same name as the one in the parent class, thus hiding it (not recommended).
    • You can declare new fields in the child class that are not in the parent class.
    • The inherited parent class methods can be used directly as they are.
    • You can write a methods in child class that has the same signature as the one in the parent class. i.e Method Overriding.
    • You can write a new static method in the child class with the same signature as on the parent class, thus hiding it.
    • You can declare new methods in the child class that are not in the parent class.
    • You can write a child class constructor that invokes the constructor of the parent class, either implicitly or by using the keyword super.

    Example of Inheritance

    In this example, Animal is a parent class which is extended by the Dog Child class. The animal class having properties name, breed, age and color. There is one method print() to print all these values. Dog subclass will inherit all these properties those having access modifiers as public and protected. Child class Dog print() method is calling parent class print() method by super keyword.

    Java inheritance Example
    Java Inheritance Example

    //POJO Class
    public class Animal {
    	// private variables
    	private String name;
    	private String breed;
    	private int age;
    	private String color;
    
    	// Getter and setter methods
    	public Animal(String name, String breed, int age, String color) {
    		this.name = name;
    		this.breed = breed;
    		this.age = age;
    		this.color = color;
    	}
        //Method of class
    	public String print() {
    		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
    	}
    }
    
    public class Dog extends Animal {
    	private String type;
    
    	public Dog(String name, String breed, int age, String color, String type) {
    		// call super class constructor to initialize
    		super(name, breed, age, color);
    		this.type = type;
    	}
    
    	// Overriding method of parent class
    	@Override
    	public String print() {
    		return "Dog [type=" + type + ", print()=" + super.print() + "]";
    	}
    }
    
    public class TestInheritance {
    
    	public static void main(String[] args) {
    
    		 //Instance with Parameterize Constructor
    	     Animal dog=new Animal("Tommy","Small Dog",5,"Black");
    	     //calling super class method because reference to super class
    	     System.out.println(dog.print());
    
    	     Animal dog_tiny=new Dog("Tiny","Small Dog",4,"Black","Bichon Friese");
    	     //calling super class method because reference to super class
    	     System.out.println(dog_tiny.print());
    
    	     Dog dog_big=new Dog("Tufan","Big Dog",4,"White","Spotted");
    	     //calling sub class method because reference to sub class
    	     System.out.println(dog_big.print());
    	}
    }
    

    Output

    
    Animal [name=Tommy, breed=Small Dog, age=5, color=Black]
    Dog [type=Bichon Friese, print()=Animal [name=Tiny, breed=Small Dog, age=4, color=Black]]
    Dog [type=Spotted, print()=Animal [name=Tufan, breed=Big Dog, age=4, color=White]]
    

    Here from this output, you will see the print method called based on object not by references of the object.

    Points about Inheritance

    • extends the keyword used to implement inheritance.
    • Java doesn’t support multiple inheritances. It’s possible by implementing multiple interfaces.
    • Inheritance has an “IS-A” relationship.
    • Excepting Object Class, which has no parent class, every class has one and only one direct parent class (single inheritance). In the absence of any other explicit parent class, every class is implicitly a child class of Object.

    Type of Inheritance in Java

    Java supports three types of inheritance only for classes:

    1. Single
    2. Multi-Level
    3. HierarchicalJava Types Of Inheritance

    Note:

    • Multiple Inheritance is not supported in java through the class.
    • Multiple and Hybrid inheritance is supported in java through interface only.

    Single Level Inheritance

    As you have seen in the above example is a single level of inheritance.

    Multi-Level Inheritance

    class Animal{
    void eat(){System.out.println("Animal eating...");}
    }
    class Dog extends Animal{
    void bark(){System.out.println("Dog barking...");}
    }
    class BabyDog extends Dog{
    void weep(){System.out.println("Baby Dog weeping...");}
    }
    class MultiLevelInheritanceTest{
    public static void main(String args[]){
    BabyDog d=new BabyDog();
    d.weep();
    d.bark();
    d.eat();
    }}
    

    Output

    
    Baby Dog Weepig...
    Dog barking...
    Animal eating...
    

    Hierarchical Inheritance

    class Animal{
    void eat(){System.out.println("Animal eating...");}
    }
    class Dog extends Animal{
    void bark(){System.out.println("Dog barking...");}
    }
    class Cat extends Animal{
    void meow(){System.out.println("Cat meowing...");}
    }
    class TestHierchicalInheritance3{
    public static void main(String args[]){
    Cat c=new Cat();
    c.meow();
    c.eat();
    //c.bark();//Compile Time Error
    }}
    

    Output

    
    Cat meowing...
    Animal eating...
    

    Why multiple inheritance is not supported in java?

    Java doen’t support multiple inheritance for class because of fixing ambiguity of common members like fields or method.

    Suppose, we have three claases ClassA, ClassB and ClassC where ClassC extends ClassA and ClassB which are having common method display(). If you call display() method from child class then not sure which method got called because of ambiguity.
    Since java not support multiple inheritance that’s why throgh compile time exception.

    class ClassA{
    void display(){System.out.println("Inside Class A");}
    }
    class ClassB{
    void display(){System.out.println("Inside Class B");}
    }
    //Compile time issue issue here
    class ClassC extends ClassA,ClassB{
     //suppose if it were
     public static void main(String args[]){
       ClassC obj=new ClassC();
       //Here it will through compile time issue
       obj.display();
    }
    

     

    Java: Constructors

    In Java, Constructors are used to creating and initializing the object’s state. The constructor also contains collections of statements to execute at time object creation.

    Type of Constructors:

    • Default Constructor: A Constructor without any argument.
    • Parametrize Constructor: A Constructor with a number of arguments.

    Points to Remember for Constructor

    • Constructor always has the same name as the class name in which it exists.
    • Constructor can not be used with keywords final, abstract, synchronized and static.
    • Constructors declaration with access modifiers can be used to control its access i.e so that restricts other classes to call the constructor.
    • All java classes must have at least one constructor. If you do not explicitly declare any constructor, then on time of compile Java compiler will automatically provide a no-argument constructor i.e also called the default constructor.
    • If you declare any parameterize constructor then that is must write a default constructor.
    • This default constructor calls the parent’s class no-argument constructor i.e super(); or if no parent class extended the called constructor of Object Class i.e directly or indirectly parent class of all the class.

    Example of Constructors

    //Class Declaration
    public class Animal {
    	//instance variables
        String name;
        String breed;
        int age;
        String color;
    
        //Default Constructor : Constructor without parameter
        public Animal()
        {
        this.name="Default";
        }
    
       // Parameterize Constructor : Constructor with parameter
        public Animal(String name, String breed,
                       int age, String color)
        {
            this.name = name;
            this.breed = breed;
            this.age = age;
            this.color = color;
        }
    	//Parameterize constructor
    	//Constructor Overriding
    	public Animal(String name, String breed)
        {
            this.name = name;
            this.breed = breed;
        } 
    
    }
    

    Object Creation By Constructor

    Here you will see both ways to create objects of Animal Class by using the default and parameterize constructors.

    public TestClass
    {
    	public static void main(String[] args)
    	{
    	 //Instance Default Constructor
    	 Animal dog_tommy=new Animal();
    
    	 //Instance with Parameterize Constructor
         Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");
    	}
    }
    

    Does the Constructor return any value?

    A constructor doesn’t have return type while implementation, but the constructor returns the current instance of the class. We can write return statements inside the class.

    Constructor Overloading

    Similar to methods, we can overload constructors also by creating an object in many ways. Java compiler differentiates between these constructors based on signature (i.e numbers, type, and order of parameters).

    What is Constructor Chaining?

    Constructor chaining is the process of calling a constructor from another constructor for the current object.

    Constructor chaining can be performed in two ways:

    • Within the same class: Use this() keyword for same class constructors.
    • From base class: Use super() keyword to call a base class constructor.

    Rules of constructor chaining

    • The this() expression should always be the first line of statment in the constructor.
    • There should always be at least one constructor without this() keyword.
    • Constructor chaining can be performed in any order.

    Constructor Chaining Example: Within Same Class

    Use this() keyword for constructors in the same class. Here you will see the last constructor with two arguments calling the constructor with the keyword this() for four arguments.

    //Class Declaration
    public class Animal {
    	//instance variables
        String name;
        String breed;
        int age;
        String color;
    
        //Default Constructor : Constructor without parameter
        public Animal()
        {
        this.name="Default";
        }
    
       // Parameterize Constructor : Constructor with parameter
        public Animal(String name, String breed,
                       int age, String color)
        {
            this.name = name;
            this.breed = breed;
            this.age = age;
            this.color = color;
        }
    	//Parameterize constructor
    	//Constructor Overriding
    	public Animal(String name, String breed)
        {
    	   //constructor chaining
    	    this(name,breed,1,"black");
        }
    }
    

    Constructor Chaining Example: From Base Class

    Use super() keyword to call a constructor from the base class. Here Constructor chaining occurs through inheritance. A sub-class constructor’s call the super class’s constructor first so that sub class’s object starts with the initialization of the data members of the superclass. There could be multilevel of classes in the inheritance chain. Every subclass constructor calls up the chain till class at the top is reached.

    
    public class Person{
        private String name;
        protected String citizenship;
    
        public Person()
        {
        }
    
        public Person(String name, String citizenship) {
            super();
            this.name = name;
            this.citizenship = citizenship;
        }
    
        public void print() {
    		System.out.println("Citizen:"+ citizenship + ",Name:" + name);
    	}
    
    }
    

     

    public class Employee extends Person {
    	private int employeeId;
    	private String department;
    	private int salary;
    
    	public Employee() {
    
    	}
    
    	public Employee(int employeeId, String name, String department, String citizen) {
    			}
    
    	public Employee(int employeeId, String name, String department, String citizen, int salary) {
    		// super keyword use to call parent constructor
    		//constructor chaining to parent class
    		super(name, citizen);
    		this.employeeId = employeeId;
    		this.department = department;
    		this.salary = salary;
    		System.out.println("Employee Constructor Executed.");
    	}
    
    }
    

    What is the use of constructor chaining?

    Constructor chaining is the mechanism to perform multiple tasks in a single constructor rather than creating a separate constructor for each task and make their chain. Constructor Chaining makes the program more readable.

    Constructors Vs Methods

    Constructor Method
    Constructor(s) must have the same name as the class within which it defined. The method does not have the same name as the class in which defined.
    Constructor(s) does not return any type. method(s) have the return type or void if does not return any value.
    A constructor is called only once at the time of Object creation. Method(s) can be called any number of times.
    In case constructor not present in class, the default constructor provided by the compiler. In the case of Method, the compiler doesn’t provide the default method.
    Constructs invoked implicitly Methods invoked explicitly.

    Java: Object

    Pre-Requisite: Java:Class
    In the previous post, you learn about the Java Class declaration, implementation, and types of classes. Here we will discuss Object which is the basic unit of Object-Oriented paradigm to represent real-life entities.

    When an instance of a class is created is known as Object. These instances share attributes and behaviors i.e methods of the class. These values of attributes will be unique for each object i.e called state.

    A java program may have lots of objects and these objects interact with each other by invoking methods. An object consists of :

    • Identity: It gives a unique name to the identification of an object and enables one object to interact with other objects.
    • State: It is represented by attributes/properties values of an object.
    • Behavior: It is represented by methods of an object to behave in a particular state.

    Object Class

    Let’s consider a class of Animal, which can have an object like Dog, Cow, Lion, Elephant, etc. Each of these animals has different properties like name, breed, age, and color.

    //Class Declaration
    public class Animal {
    	//instance variables
        String name;
        String breed;
        int age;
        String color;
    
        //Default Constructor : Constructor without parameter
        public Animal()
        {
        this.name="Default";
        }
    
       // Parameterize Constructor : Constructor with parameter
        public Animal(String name, String breed,
                       int age, String color)
        {
            this.name = name;
            this.breed = breed;
            this.age = age;
            this.color = color;
        } 
    
        //Instance methods
        public String getName()
        {
            return name;
        } 
    
        public String getBreed()
        {
            return breed;
        } 
    
        public int getAge()
        {
            return age;
        } 
    
        public String getColor()
        {
            return color;
        }
        //methods override from Object class
    	@Override
    	public String toString() {
    		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
    	}
    }
    

    Example of an object: Dog

    Declaration of Object

    We declare a variable or object like (type variable_name;). This indicates to the compiler that this variable refers to data whose type is type. In the case of the primitive type, declaration allocates space for the variable as per type but in case of a reference variable, the type must be a concrete class name. Generally, In java, we don’t create an object of Abstract class and interface.

    Syntax

    access_modifier class_name object_name;

    Example

    Animal dog_tommy;

    As declared above for variable dog_tommy, show this variable is of type Animal but this will not create any object instance i.e point to undetermined value (null) as long as an object not created.

    Creation & Initializing an object

    When we create an instance of an object by using the new operator. It will allocate memory for a new object and return a reference to that memory. This new operator also called the class constructor to initialize the attributes of the class.

    Syntax

    //default constructor
    access_modifier class_name object_name=new class_name();
    //parameterize constructor
    access_modifier class_name object_name=new class_name(arg1,arg2..);

    Example

    //Default Constructor
    Animal dog_tommy=new Animal();
    
    //Parameterize Constructor
    Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");

    Note :

    • All classes have at least one constructor. If you do not explicitly declare any constructor, then on time of compile Java compiler will automatically provide a no-argument constructor i.e also called the default constructor.
    • If you declare any parameterize constructor then that is must write a default constructor.
    • This default constructor calls the parent’s class no-argument constructor i.e super(); or if no parent class extended the called constructor of Object Class i.e directly or indirectly parent class of all the class.

    Complete Example

    //Class Declaration
    public class Animal {
    	//instance variables
        String name;
        String breed;
        int age;
        String color;
    
        //Default Constructor : Constructor without parameter
        public Animal()
        {
        this.name="Default";
        }
    
       // Parameterize Constructor : Constructor with parameter
        public Animal(String name, String breed,
                       int age, String color)
        {
            this.name = name;
            this.breed = breed;
            this.age = age;
            this.color = color;
        } 
    
        //Instance methods
        public String getName()
        {
            return name;
        } 
    
        public String getBreed()
        {
            return breed;
        } 
    
        public int getAge()
        {
            return age;
        } 
    
        public String getColor()
        {
            return color;
        }
        //methods override from Object class
    	@Override
    	public String toString() {
    		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
    	}
    }
    
    public TestClass
    {
    	public static void main(String[] args)
    	{
    	 //Instance Default Constructor
    	 Animal dog_tommy=new Animal();
    
    	 //Instance with Parameterize Constructor
         Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");
    	}
    }
    

    Output

    
    Animal [name=Default, breed=null, age=0, color=null]
    Animal [name=Tommy, breed=Small Dog, age=5, color=Black]
    

    Ways to create an object of a class

    This is the most common way to create an instance of an object by using new operators. Java also provides other ways to create instances of an object but internally uses a new keyword only.

    1. Object by new Operator
    2. Object by Class.forName().newInstance()
    3. Object by clone() method
    4. Object by Deserialization
    5. Object for Anonymous Class

    Follow this link to know about each object creation ways in detail: Java: Object Creation Ways

     

    Java: Types of Classes

    Pre-Requisite: Java: Class
    In a previous post, you have got an understanding of java class declaration and creation.

    Types of classes

    Java supports lots of types of classes:

    • Concrete Class
    • Abstract Class
    • POJO Class
    • Static Class
    • Nested Class/Inner Class
    • Final Class
    • Anonymous Class
    • Lambda Expression

    Here we will discuss these classes in detail.

    Concrete Class

    A concrete class is a normal class that is not declared with Non-access modifiers as abstract, final, etc. This class can have an implementation of a parent, interfaces or own class methods.

    Example: Concrete Class

    //Example Concrete Class
    public class CalculatorTest {
        static int add(int a , int b)
        {
        	return a+b;
        }
        static int substract(int a , int b)
        {
        	return a-b;
        }
        static int multiply(int a , int b)
        {
        	return a*b;
        }
        static int division(int a , int b)
        {
        	return a/b;
        }
    	public static void main(String[] args) {
          System.out.println("4+5 ="+add(4,5));
          System.out.println("4-5 ="+substract(4,5));
          System.out.println("4*5 ="+multiply(4,5));
          System.out.println("4/5 ="+division(4,5));
    	}
    }
    

    See Also: Java: Concrete Class Examples

    Abstract Class

    A class that is declared with the keyword abstract is known as an abstract class in Java. It can have abstract and concrete methods (method with the body). An abstract class can not be instantiated but need to extend to implement abstract methods.

    Example: Abstract Class

    args)
    {
    Vehicle v=new Car();
    v.engine();
    v=new Bike();
    v.engine();
    v=new Truck();
    v.engine();
    v=new Bus();
    v.engine();
    }
    }

    See Also: Java: Abstract Class Examples

    POJO Class

    A class with only private variables and public getter and setter methods is called as POJO(Plain Old Java Object) class. These getter and setter methods use private variables. This class is completely encapsulated.

    Example: Pojo Class

    //POJO Class
    public class Animal {
    	//private  variables
        private String name;
        private String breed;
        private int age;
        private String color;
        //Getter and setter methods
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getBreed() {
    		return breed;
    	}
    	public void setBreed(String breed) {
    		this.breed = breed;
    	}
    	public int getAge() {
    		return age;
    	}
    	public void setAge(int age) {
    		this.age = age;
    	}
    	public String getColor() {
    		return color;
    	}
    	public void setColor(String color) {
    		this.color = color;
    	}
    }
    

    See Also: Java: Pojo Class Examples

    Static Class

    A static class is a nested class declared as a static member of the class.

    Example: Static Class

    import java.util.Scanner;
    
    public class StaticClasses {
    	static int s;// static variable
    
    	// static method
    	static void printSum(int a, int b) {
    		s = a + b;
    		System.out.println(a + "+" + b + "=" + s);
    	}
    
    	static class NestedStaticClass//static class
    	{
    		static//static block
    		{
    			System.out.println("Inside Nested Class Static Block");
    		}
    
    		public void display()
    		{
    			Scanner scanner=new Scanner(System.in);
    			System.out.println("Enter value of a:");
    			int a= scanner.nextInt();
    			System.out.println("Enter value of b:");
    			int b= scanner.nextInt();
    
    			printSum(a,b);
    			System.out.println("Sum of numbers a+b:" +s);
    
    		}
    	}
    }
    
    public class StaticClassTest {
    
    	public static void main(String[] args) {
    		StaticClasses.NestedStaticClass nss=new StaticClasses.NestedStaticClass();
    		//call method of nested class method
    		nss.display();
    	}
    }
    

    See Also: Java: Static Keyword & Examples

    Nested Class/Inner Class

    A Class declared inside of another class is called Nested Class/Inner Class.

    Example: Nested Class/Inner Class

    public class OuterClass {
    
    	//nested/Inner Class: Class inside the class
    	class NestedClass
    	{
    		public void innerMethod()
    		{
    			System.out.println("Inner Class Print");
    		}
    	}
    
    	public static void main(String[] args) {
    		System.out.println("Outer Class Print");
    
    	}
    
    }
    

    See Also: Java: Nested/Inner Class Examples

    Final Class

    A Class declared with the final keyword is known as Final Class. This class can not be extended by another class. For Example java.lang.System, java.lang.String

    Example: Final Class

    public final class FinalClass {
     public void display()
     {
    	 System.out.println("Display final class method.");
     }
    }
    
    //show compiler error :
    //"The type BaseClass can not subclass the final class FinalClass"
    class BaseClass extends FinalClass{
    	public void display()
    	 {
    		 System.out.println("Display base class method.");
    	 }
    }
    

    See Also: Java: Final Keyword & Examples

    Anonymous Inner Class

    Anonymous Class is an inner class without a name and for which only a single object is created. Such class is useful when you need to create an instance of an object such as overloading methods of a class or interface, without having to actually subclass a class.

    Anonymous inner classes are mostly used in writing implementation classes for listener interfaces in graphics programming.

    Example: Anonymous Class

    //Using Anonymous Inner class Thread that extends a Class
    class MyThread
    {
        public static void main(String[] args)
        {
            //Here we are using Anonymous Inner class
            //that extends a class i.e. Here a Thread class
            Thread t = new Thread()
            {
                public void run()
                {
                    System.out.println("Child Thread");
                }
            };
            t.start();
            System.out.println("Main Thread");
        }
    }
    

    See Also: Java: Anonymous Class Examples

    Lambda Expression

    Lambda expressions added in Java 8. It useful to create instances of functional interfaces (An interface with single abstract method). For Example: java.lang.Runnable is having one abstract method as run().

    Example: Lambda Expression

    public class LamdaTest {
    	public static void main(String[] args) {
    		new Thread(() -&gt; System.out.println("This is Lamda test")).start();
    	}
    }
    

    See Also: Java: Lamda Expression Examples

     

    Java: Class

    A Class is a blueprint or prototype from which objects are created. A class has properties and behaviors i.e methods that are common to all objects of the same type.

    Object Class

    Syntax of Class Declaration

    
    Access_Modfier Non_access_modiers class class_name 
        extends super_class 
        implements interface1, interface 2..
    {
    fields
    ......
    default constructor
    ......
    parametrize constructor
    ......
    methods
    ......
    }
    
    • Access Modifiers: A modifier defined access scope of class, fields, and methods. If specifically not mentioned consider as default. See Also: Java: Access Modifiers/Specifiers
    • Class name: The class name should begin with an initial capital letter follow camel notation. See Also: Java: Identifier Naming Conventions
    • Non-Access Modifiers (if any): non-access modifiers can also be used on the class level to make a class special. See Also: Java: Non-Access Modifiers
    • Superclass(if any): A class can extend only one class i.e called parent class or superclass.
    • Interfaces(if any): A class can implement one or more interfaces. Their interfaces proceed by keyword implements and separated by a comma.
    • Body: A class body is surrounded by curly braces, { }.
      Fields: A class fields are variables that provide the state of class and it’s objects.
    • Methods: class methods are defined to implement the behavior of class and objects. See Also: Java Methods
    • Constructors: Java class constructors are used to initialize new objects. See Also: Java: Constructors

    Note:

    • If a class is declared with access modifier public then java file name would also be the same. One Java file can have only one public class.
    • All the class extends Object Class i.e Object class is the superclass of all the classes.See Also: Java: java.lang.Object Class & Methods

    Java Class Example

    This is a very simple example of a class name as Animal. It’s having variables, constructors, methods and overriding method of superclass Object.

    //Class Declaration
    public class Animal {
    	//instance variables
        String name;
        String breed;
        int age;
        String color;
    
        //Default Constructor : Constructor without parameter
        public Animal()
        {
        this.name="Default";
        }
    
       // Parameterize Constructor : Constructor with parameter
        public Animal(String name, String breed,
                       int age, String color)
        {
            this.name = name;
            this.breed = breed;
            this.age = age;
            this.color = color;
        } 
    
        //Instance methods
        public String getName()
        {
            return name;
        } 
    
        public String getBreed()
        {
            return breed;
        } 
    
        public int getAge()
        {
            return age;
        } 
    
        public String getColor()
        {
            return color;
        }
        //methods override from Object class
    	@Override
    	public String toString() {
    		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
    	}
    }
    

    Now we have got a basic understanding of class declaration and implementation. In the further post, you will learn about the types of classes and uses.

    Types of classes

    Java supports lots of types of classes:

    • Concrete Class
    • Abstract Class
    • POJO Class
    • Static Class
    • Nested Class/Inner Class
    • Final Class
    • Anonymous Class
    • Lambda Expression

    Follow this link to know about all these classes and uses.

    See Also: Java: Type of classes

    Java: StringBuilder Class & Examples

    Java StringBuilder is used to create a mutable String object. It’s introduced in JDK 1.5. It’s similar to StringBuffer class the only difference is non-synchronized and no thread-safe.

    See Also: String Vs StringBuffer Vs StringBuilder

    Constructors of StringBuilder class

    Constructor Description
    StringBuilder() creates an empty string Builder with the default initial capacity of 16.
    StringBuilder(String str) creates a string Builder with the given string.
    StringBuilder(int length) creates an empty string Builder with the given capacity as length.

    Methods of StringBuilder class

    Method Description 
    public StringBuilder append(String s) Append the specified string with current string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
    public StringBuilder insert(int offset, String s) Insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
    public StringBuilder replace(int startIndex, int endIndex, String str) Replace the string from the specified startIndex and endIndex.
    public StringBuilder delete(int startIndex, int endIndex) Delete the string from the specified startIndex and endIndex.
    public StringBuilder reverse() Reverse the string.
    public int capacity() Return the current capacity of String builder.
    public void ensureCapacity(int minimumCapacity) Ensure the capacity at least equal to the given minimum then only increase capacity.
    public char charAt(int index) Return the character at the specified index position.
    public int length() return the total count of the characters in string.
    public String substring(int startIndex) is used to return the substring from the specified startIndex.
    public String substring(int startIndex, int endIndex) is used to return the substring from the specified startIndex and endIndex.

    Example: StringBuilder append() method

    Java StringBuilder append() method used to concatenates the given argument with this string.

    StringBuilder sb=new StringBuilder("Facing Issues On ");
    sb.append("IT");//Original String will change
    System.out.println(sb);//new string "Facing Issues On IT"
    

    Example: StringBuilder insert() method

    Java StringBuilder insert() method used to insert the given string at the given position.

    StringBuilder sb=new StringBuilder("Facing On IT");
    sb.insert(6," Issues ");//insert string on 6th position
    System.out.println(sb);//new string "Facing Issues On IT"
    

    Example: StringBuilder replace() method

    Java StringBuilder replace() method used to replaces the given string from the specified startIndex and endIndex.

    StringBuilder sb=new StringBuilder("Facing Saurabh On IT");
    sb.replace(7,14,"Issues");//replace saurabh with  issues
    System.out.println(sb);//new string "Facing Issues On IT"
    

    Example: StringBuilder delete() method

    Java StringBuilder delete() method use to deletes the string from the specified startIndex to endIndex..

    StringBuilder sb=new StringBuilder("Facing Saurabh On IT");
    sb.delete(7,14);//delete saurabh
    System.out.println(sb);//new string "Facing  On IT"
    

    Example: StringBuilder reverse() method

    Java StringBuilder reverse() method used to reverses the current string.

    StringBuilder sb=new StringBuilder("Facing Saurabh On IT");
    sb.reverse();
    System.out.println(sb);//new string "TI no seussI gnicaF"
    

    See Also: Java: Ways to reverse String

    Example: StringBuilder capacity() method

    Java StringBuilder capacity() method use to returns the current capacity of the Builder. The default capacity of the Builder is 16. If the number of the character increases from its current capacity, it increases the capacity by (oldcapacity2)+2. For example, Suppose your current capacity is 16, then the next capacity will be (162)+2=34.

    StringBuilder sb=new StringBuilder();
    System.out.println(sb.capacity());//default 16
    sb.append("Facing Issues On IT");
    System.out.println(sb.capacity());//now (16*2)+2=34 i.e (old_capacity*2)+2
    sb.append("Learn from Others Experinces");
    System.out.println(sb.capacity()); //now (34*2)+2=70 i.e (old_capacity*2)+2
    

    Example: StringBuilder ensureCapacity() method

    Java StringBuilder ensureCapacity() method use to ensures that the given capacity is the minimum to the current capacity. If it is greater than the ensure capacity, it increases the capacity by (oldcapacity2)+2. For example, Suppose your current capacity is 16, then the next capacity will be (162)+2=34.

    StringBuilder sb=new StringBuilder();
    System.out.println(sb.capacity());//default 16
    sb.ensureCapacity(40);//Now Capacity will increase when reach to 40
    sb.append("Facing Issues On IT");
    System.out.println(sb.capacity());//because of ensure capacity capacity will 40 only
    sb.append("Learn from Others Experinces");
    System.out.println(sb.capacity()); //now (40*2)+2=82 i.e (oldcapacity*2)+2
    

     

    Java: EnumSet Class

    Java EnumSet class is the specialized Set implementation for use with enum types. It inherits AbstractSet class and implements the Set interface.

    EnumSet class hierarchy

    The hierarchy of EnumSet class is given in the figure given below.
    EnumSet

    EnumSet class declaration

    Let’s see the declaration for java.util.EnumSet class.

    public abstract class EnumSet<E extends Enum> extends AbstractSet implements Cloneable, Serializable  
    

    Methods of Java EnumSet Class

    Method Description
    static <E extends Enum> EnumSet allOf(Class elementType) It is used to create an enum set containing all of the elements in the specified element type.
    static <E extends Enum> EnumSet copyOf(Collection c) It is used to create an enum set initialized from the specified collection.
    static <E extends Enum> EnumSet noneOf(Class elementType) It is used to create an empty enum set with the specified element type.
    static <E extends Enum> EnumSet of(E e) It is used to create an enum set initially containing the specified element.
    static <E extends Enum> EnumSet range(E from, E to) It is used to create an enum set initially containing the specified elements.
    EnumSet clone() It is used to return a copy of this set.

    Example :EnumSet

    import java.util.*;
    enum days {
      SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
    }
    public class EnumSetExample {
      public static void main(String[] args) {
        Set set = EnumSet.of(days.TUESDAY, days.WEDNESDAY);
        // Traversing elements
        Iterator iter = set.iterator();
        while (iter.hasNext())
          System.out.println(iter.next());
      }
    }
    

    Output :

    
    TUESDAY
    WEDNESDAY
    

    Java EnumSet Example: allOf() and noneOf()

    import java.util.*;
    enum days {
      SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
    }
    public class EnumSetExample {
      public static void main(String[] args) {
        Set set1 = EnumSet.allOf(days.class);
          System.out.println("Week Days:"+set1);
          Set set2 = EnumSet.noneOf(days.class);
          System.out.println("Week Days:"+set2);
      }
    }
    

    Output :

    
    Week Days:[SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
    Week Days:[]