Category Archives: Java Program

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

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

[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

[Java] How to reverse String in Java?

In java, we can reverse String in java by so many ways as given below:

  1. StringBuffer
  2. StringBuilder
  3. Character Iteration

Reverse String in Java: By StringBuffer

public class ReverseStringExample1 {
public static String reverseString(String str){
StringBuffer sb=new StringBuffer(str);
//String buffer in-built method
sb.reverse();
return sb.toString();
}
}

Reverse String in Java: By StringBuilder

public class ReverseStringExample2 {
public static String reverseString(String str){
StringBuilder sb=new StringBuilder(str);
//String builder in-built method
sb.reverse();
return sb.toString();
}
}

Reverse String in Java: By Character Iteration

public class ReverseStringExample3 {
public static String reverseString(String str){
char ch[]=str.toCharArray();
String rev="";
//run loop in reverse order for each character
for(int i=ch.length-1;i&gt;=0;i--){
rev+=ch[i]; //append characters
}
return rev;
}
}

Complete Example: Reverse String In Java

Here consolidated all the ways to reverse String in Java.

public class TestStringInJava {
public static void main(String[] args) {
System.out.println(ReverseStringExample1.reverseString("My Name is Saurabh."));
System.out.println(ReverseStringExample2.reverseString("Facing Issues on IT"));
System.out.println(ReverseStringExample3.reverseString("Learn From Others Experinces"));
}
}
}

Output

.hbaruaS si emaN yM
TI no seussI gnicaF
secnirepxE srehtO morF nraeL

 

Java: Program execution from Command Line and Eclipse with Arguments.

In the previous post First Java “Hello World” Program, you got some basic understanding for starting a Java Program. In this post, you will learn about to execute a Java Program from Eclipse and Commandline. Here consider both the case by passing with and without arguments to the main method().

Points to Remember

These are some points that need keep in mind while passing arguments from the eclipse or command line.

  • When you need to pass more than one argument. These values separated by spaces.
  • If passing an argument String value having space make sure to pass in the double quote (” “). For Example: “Saurabh Gupta”.
  • Always check for the length of  main() method argument otherwise you may get ArrayIndexOutOfBoundException if trying to access index beyond passed arguments.

Execute Java Program from Eclipse without Arguments

When your program not required any argument to pass in main() methods follow these steps to execute a program.

For Example :

public class TestProgram {

public static void main(String[] args) {
System.out.println("Hello World ! ");
}
}

Output


Hellow World !
  • Step 1: Go to the Java Class file  “TestProgram”.java.
  • Step 2: Right-click on the file select option as  “Run As” -> “Java Application”.
  • Step 3: You will see the output in the console tab.

Execute Java Program from Eclipse with Arguments

When your program required arguments to pass in the main() method follow these steps to execute a program.

For Example:

In this program, main() method required three arguments to print for “First Name “, “Last Name ” and “Full Name”.

public class TestProgram {

public static void main(String[] args) {
System.out.println("Hello World ! ");

System.out.println("Number of argument passed :"+args.length);
//Check for number of argument passed from command line
if (args != null &amp;&amp; args.length == 3) {
System.out.println("First Name :" + args[0]);
System.out.println("Last Name :" + args[1]);
System.out.println("Full Name :" + args[2]);
}
}
}

Output


Hello World ! 
Number of argument passed :3
First Name :Saurabh
Last Name :Gupta
Full Name :Saurabh Gupta
  • Step 1: Go to the Java Class file  “TestProgram”.java.
  • Step 2: Right-click on the file select option as  “Run As” -> “Run Configuration”.
  • Step 3: You will get pop up, Go to the “Arguments” tab pass arguments in the “Program Arguments” section as mentioned in the below screen for this example.
  • Step 4: Click on the Run Button.
  • Step 3: You will see the output in the console tab.

Eclipse Arguments Passing to java program

ss

ss

Java Program run from command line.jpg

 

 

ss

java program run commandline with argument

Frequently Asked Algorithms & Java Programs

Below are most frequently asked algorithms and programs in interview to test interviewee programming and logical skill. These question can be asked with fresher and any senior level programmers to check hands on with the code or not.

  1. Write a program to print alphabet using java loop
    Output:
    a b c d e f g h i j k l m n o p q r s t u v w x y z
    a b c d e f g h i j k l m n o p q r s t u v w x y z
    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
  2. Write a program to check odd or even number.
    Input:  5
    Output: Odd Number
  3. Write a program to convert Fahrenheit to Celsius.
    Input: 50
    Output: 10.0
  4. Write a java program to print fibonacci series without using recursion and using recursion.
    Input: 12
    Output: 0 1 1 2 3 5 8 13 21 34 55 89 144
  5. Write a java program to check prime number.
    Input: 42
    Output: Not prime number
    Input: 13
    Output: Prime number
  6. Write a java program to check palindrome number.
    Input: 349
    Output: Not palindrome number
    Input: 1234321
    Output: Palindrome number
  7. Write a java program to print factorial of a number.
    Input: 4
    Output: 24
    Input: 5
    Output: 120
  8. Write a java program to check Armstrong number.
    Input: 153
    Output: Armstrong number
    Input: 22
    Output: Not Armstrong number
  9. Write a program to swap numbers without using third variable.
    Input: 20 30
    Output: 30 20
  10. Write a program to reverse of number.
    Input:    123456
    Output: 654321
  11. Write a program to find largest of three numbers.
    Input: 10 30 40
    Output: 40
  12. Write a program to print Floyd triangle.
    Input: 7
    Output:

    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

Sorting Program

  1. Write a java program to sort an array elements using bubble sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  2. Write a java program to sort an array elements using selection sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  3. Write a java program to sort an array elements using insertion sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  4. Write a java program to sort an array elements using quick sort algorithm.
    Input:    12 24 45 56 10 9 49 30 5 15
    Output: 5 9 10 12 15 24 30 45 49 56
  5. Write a java program to sort an array elements using heap sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  6. Write a java program to sort an array elements using merge sort algorithm.
    Input:    12 24 45 56 10 9 49 30 5 15
    Output: 5 9 10 12 15 24 30 45 49 56
  7. Write a java program to sort an array elements using shell sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  8. Write a java program to sort an array elements using radix sort algorithm.
    Input:   170 45 75 90 2 802 2 66
    Output: 2 2 45 66 75 90 170 802
  9. Write a java program to sort an array elements using bucket sort algorithm.
    Input:   0.23 0.67 0.32 0.25 0.88 0.45 0.86 0.16 0.59 0.38 0.19 0.43 0.02
    Output: 0.02 0.16 0.19 0.23 0.25 0.32 0.38 0.43 0.45 0.59 0.67 0.86 0.88
  10. Write a java program to sort an array elements using counting sort algorithm.
    Input:    2 6 3 2 8 4 8 1 5 3 1 4 0
    Output: 0 1 1 2 2 3 3 4 4  5 6 8 8

Java Searching Programs

  1. Write a java program to perform linear search in java.
  2. Write a java program to perform binary search in java.

Fibonacci Series Java Program

“A fibonacci series is sequence of numbers, where each number is sum of the two preceding two numbers, Series initial two values are 1 , 1″

For Example : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144………

Fibonacci Series Program

Here is program to get Fibonacci series number on particular position and print series up to that point. In this program using recursion to generate Fibonacci numbers, Here put base condition to terminate recursion as when number reach to 1 or 2  and for rest of the case work recursively for current number and previous one and then add it.

import java.util.HashMap;
import java.util.Map;

public class FibonacciSeriesExample {

private static Map series = new HashMap();

public static void main(String[] args) {

// Get the 12th fibonacci number from series
System.out.println("Fibonacci 12 the position element :" + fibonacci(12));

System.out.println("Print Complete Fibonacci Series :");
printFibonacci(series);
}

public static int fibonacci(int fibIndex) {

// set base element of fibonacci series
if (fibIndex == 1 || fibIndex == 2) {
series.put(1, 1);
series.put(2, 1);
}

// execute fibonacci recursively until fibIndex reach to 1
if (series.containsKey(fibIndex)) {
return series.get(fibIndex);
} else {
int answer = fibonacci(fibIndex - 1) + fibonacci(fibIndex - 2);
series.put(fibIndex, answer);
return answer;
}
}

public static void printFibonacci(Map series) {

for (Map.Entry entry : series.entrySet()) {
System.out.println(entry.getValue());
}
}
}

Output


Fabonnici 12 the position element :144
Print Complete Fabonni Series :
1
1
2
3
5
8
13
21
34
55
89
144

Merge Sort Program and Complexity (Big-O)

Mergesort is a comparison sort, same as quicksort and based on divide and conquer algorithm. It divides the original data set into smaller pieces of data set to solve the problem and then finally merge these small data sets.

How Merge Sort Works

Merge sort works in the following way:

  1. Merge sort, take middle index in data set and split into two collections : one collection for items left of middle index and second for right values of middle index.
  2. Repeat step 1 as long as these collections size reach to one item only.
  3. Now merge sort picks the items from smaller collections, sort them and merge to create new collection.
  4. Repeat this sort and merge process until all small colection sort and merge not completed.
  5. Finally will get single collection with sorted result.

Points to Remember

  • Data Structure: Array
  • Best Time Complexity: Ω(n log(n))
  • Average Time Complexity: Θ(n log(n))
  • Worst Time Complexity: O(n log(n))
  • Worst Space Complexity: O(n)

Merge Sort

Merge Sort Program

public class MergeSort {

public int[] sort(int [] array){
mergeSort(array, 0, array.length-1);
return array;

}

private void mergeSort(int[] array, int first, int last) {

// Get mid position to divide problem into smaller size collections
int mid = (first + last) / 2;

//If first &lt; last the array must be recursively sorted
if (first &lt; last) {
mergeSort(array, first, mid);
mergeSort(array, mid + 1, last);
}

//merge solved collections to get solution to original problem
int a = 0, f = first, l = mid + 1;
int[] temp = new int[last - first + 1];

//decide the swapping of items
while (f &lt;= mid &amp;&amp; l &lt;= last) {
temp[a++] = array[f] &lt; array[l] ? array[f++] : array[l++];
}

while (f &lt;= mid) {
temp[a++] = array[f++];
}

while (l &lt;= last) {
temp[a++] = array[l++];
}

a = 0;
while (first &lt;= last) {
array[first++] = temp[a++];
}
}

public static void printArray(int[] array) {
for (int i = 0; i &lt; array.length; i++) {
System.out.print(array[i] + &quot; &quot;);
}

}

public static void main(String[] args) {

System.out.println(&quot;Original array before Merge sort&quot;);
int[] items = {12, 24, 45, 56, 10, 9, 49, 30, 5, 15};
printArray(items);

System.out.println(&quot;\n\nAfter Mergesort&quot;);
MergeSort merge = new MergeSort();
merge.sort(items);
printArray(items);

}
}

Output


Original array before Merge sort
12 24 45 56 10 9 49 30 5 15 

After Mergesort
5 9 10 12 15 24 30 45 49 56 

 

[Sorting] Quicksort Program and Complexity (Big-O)

Quicksort is a comparison sort based on divide and conquer algorithm. Quick sort is more fast in comparison to Merge Sort ot Heap Sort. It’s not required additional space for sorting.

How Quick Sort Works

The idea to implement Quicksort is first divides a large array into two smaller sub-arrays as the low elements and the high elements then recursively sort the sub-arrays.

The above process follow below steps:

  1. If array having 0 or 1 item then it’s already sorted.
  2. Pick an item from the array that is called as pivot.
  3. Partition this array as items less than pivot will come before pivot while items greater than pivot will come after it (equals values can either way). Now Pivot get it’s exact position.
  4. Now repeat step 2 and 3 for both left and right side values of Pivot and continue same as long as no left or right items remaining.
  5. Finally, as result of array will sorted items.

Quicksort

Points to remember

  • Data Structure: Array
  • Best Time Complexity: Ω(n log(n))
  • Time Complexity: Θ(n log(n))
  • Worst Time Complexity: O(n^2)
  • Worst Space Complexity: O(log(n))

Quick Sort Program

public class QuickSort {

public void quicksort(int[] array) {
quicksort(array, 0, array.length - 1);
}

private void quicksort(int[] array, int first, int last) {
if (first &lt; last) {
int pivot = partition(array, first, last);

// Recursive call
quicksort(array, first, pivot - 1);
quicksort(array, pivot + 1, last);
}
}

private int partition(int[] input, int first, int last) {

//choose pivot as last item
int pivot = last;

swap(input, pivot, last);
for (int i = first; i &lt; last; i++) {
if (input[i] &lt;= input[last]) {
swap(input, i, first);
first++;
}
}

swap(input, first, last);
return first;
}

private void swap(int[] input, int a, int b) {
int temp = input[a];
input[a] = input[b];
input[b] = temp;
}

public static void printArray(int[] items) {
for (int i = 0; i &lt; items.length; i++) {
System.out.print(items[i] + " ");
}
}

public static void main(String[] args) {

int[] items = {12, 24, 45, 56, 10, 9, 49, 30, 5, 15};
System.out.println("Original Array Before Quick Sort");
printArray(items);

System.out.println("\n\nAfter QuickSort");

QuickSort sort = new QuickSort();
sort.quicksort(items);
printArray(items);

}
}

Output


Original Array Before Quick Sort
12 24 45 56 10 9 49 30 5 15 

After QuickSort
5 9 10 12 15 24 30 45 49 56 

[Sorting] Radix Sort Program and Complexity (Big-O)

Radixsort sorts numeric data (integers or float) by considering a string of numbers where digit by digit sort starting from least significant digit position to most significant digit position. To sort these specific positions data counting sort as a subroutine.

Counting sort is a linear time sorting algorithm that sort in O(n+k) but that will worst in case of items range from 1 to n2 that sort in O(n^2). Where K is items range from 1 to k.

Note :

  • LSD : Least Significant Digit
  • MSD : Most Significant Digit

Steps to Radixsort

  1. Check for the max length item in input values and check for length.
  2. For each digit position i where i varies from LSD to the MSD.
  3. Perform counting sort based on considering key as i position digits.
  4. Finally, you will get a sorting array for input items.

Points to Remember

  • Data Structure: Array
  • Best Time Complexity: Ω(nk)
  • Average Time Complexity: Θ(nk)
  • Worst Time Complexity: O(nk)
  • Worst Space Complexity: O(n+k)

Radix sort Example


Input Numbers:

        170, 45, 75, 90, 02, 802, 2, 66 
Step 1 : Find the max item length in input i.e 3.

Step 2: Repeat the below process for position i from LSD to MSD
        Perform count sort on numbers, after considering digits as key on 
        particular i.
        
        0 Position :
        170, 90, 02, 802, 2, 45, 75, 66
        
        1 Position :
        02, 2, 802, 45, 66, 170, 75, 90
        
        2 Position :
        02, 2, 45, 66, 75, 90, 170, 802 
        
Step 3: Final Redix Sort result

        02, 2, 45, 66, 75, 90, 170, 802    
 

Radix Sort Program

public class RadixSort {

public static void main(String[] args) {

// Assuming our key values are with in range 0 - 9
int[] items = { 170, 45, 75, 90, 02, 802, 2, 66 };
System.out.println("Before Radix Sorting :");
printArray(items);

// Perform counting sort sort
radixsort(items);

System.out.println("After Radix Sorting :");
printArray(items);
}

// radix sort method to sort values of array items
static void radixsort(int items[]) {
// find max number to know max number of digits
int m = getMax(items);

// Perform counting sort for every digit. Note that instead
// of passing digit number, exp is passed. exp is 10^i
// where i is current digit number
for (int exp = 1; m / exp &gt; 0; exp *= 10)
countingsort(items, exp);
}

// A utility method to get maximum value in items[]
static int getMax(int items[]) {
int max = items[0];
for (int i = 1; i  max)
max = items[i];
return max;
}

private static void countingsort(int[] items, int exp) {
// create array of size 10 that will have index value as 0-9
// it will create array of size 10 and initialize
// each element with value 0
int[] counts = new int[10];
int[] output = new int[items.length];
for (int key : items) {
// for each match key, index position element
// increase count as 1
counts[(key / exp) % 10] += 1;
}

// Change count[i] so that count[i] now contains
// actual position of this digit in output[]
for (int i = 1; i = 0; i--) {
output[counts[(items[i] / exp) % 10] - 1] = items[i];
counts[(items[i] / exp) % 10] -= 1;
}

// Copy the output array to items[] to return
// sorted array according to index position
for (int i = 0; i &lt; items.length; i++)
items[i] = output[i];

}

static void printArray(int items[]) {
for (int item : items) {
System.out.print(item + " ");
}
System.out.println();
}

}

Output


Before Radix Sorting :
170 45 75 90 2 802 2 66 
After Radix Sorting :
2 2 45 66 75 90 170 802 

[Sorting] Bucket Sort Program and Complexity (Big-O)

Bucket sort/Bin sort is a distribution sort as a generalization of pigeonhole sort. It’s useful when input values are uniformly distributed over a range then divide this range in some interval and put values in a bucket which lies within these intervals.Finally, sort values in each bucket by any sorting technique and then print by sequence by iterating intervals.

Bucket Sort Steps

  1. Set up an array of empty “buckets” initially.
  2. Go over the original array, putting each item in its interval bucket.
  3. Sort all non-empty bucket.
  4. Visit each interval buckets in order and put all elements back into the original array.

Points to Remember

  • Data structure: Array
  • Best Time Complexity: Ω(n+k)
  • Average Time Complexity: Θ(n+k)
  • Worst Time Complexity: O(n^2)
  • Worst Space Complexity: O(n)

Bucket Sort Java Program

public class BucketSort {

public static void main(String[] args) {

//Assuming our key values are with in range 0 - 1
double[] items = { 0.23, 0.67, 0.32, 0.25, 0.88, 0.45, 0.86, 0.16, 0.59, 0.38, 0.19, 0.43,  0.02 };
System.out.println("Before Bucket Sorting :");
printArray(items);

//Perform counting sort sort
bucketsort(items);

System.out.println("After Bucket Sorting :");
printArray(items);
}

private static void bucketsort(double []items)
{
//create array of size 10 that will have index value as 0-9
//Initially will keep empty bucket
java.util.List []numbers=new ArrayList[10];
for(double key:items)
{
//To equally distribute input values , multiply key with array size.
int index=(int)(key*numbers.length);
//index position is not having any value yet create blank bucket
if(numbers[index]==null)
{
numbers[index]=new ArrayList();

}
//add items based on index position
numbers[index].add(key);
}

//Now sort values in each bucket by any sorting method
// and add in initial array
int i=0;
for(int index=0; index<span id="mce_SELREST_start" style="overflow:hidden;line-height:0"></span>&lt;numbers.length; index++)
{

if(numbers[index]!=null)
{
//Here i am using Collections utility method but
//you use any sorting algorithm.
Collections.sort(numbers[index]);
//iterate each value in sorted bucket
//add it in original array position
for(double  item:numbers[index])
{
items[i++]=item;
}
}

}
}

static void printArray(double items[])
{
for (double item:items)
{
System.out.print(item + " ");
}
System.out.println();
}

}

Output


Before Bucket Sorting :
0.23 0.67 0.32 0.25 0.88 0.45 0.86 0.16 0.59 0.38 0.19 0.43 0.02 
After Bucket Sorting :
0.02 0.16 0.19 0.23 0.25 0.32 0.38 0.43 0.45 0.59 0.67 0.86 0.88 

[Sorting] Shell Sort Program and Complexity (Big-O)

Shellsort is an in-place comparison sort, also known as Shell sort or Shell’s method. It’s mainly variation of insertion sort or bubble sort . There was one drawback with insertion sort, we move elements only one position ahead but when an elements are too far then lots of movements are involved. To reduce these movements Shell sort come with idea of allow exchange of far items.

Shell Sort Steps

  • Pick some far location h and make sorted array for values index[h…n-1] by insertion sort.
  • Reduce the value of h until it becomes 1.
  • Repeat the steps 1 and 2
  • Finally you will get sorted items list.

Points to Remember

  • Data structure: Array
  • Worst-case performance: O(n2) (worst known worst case gap sequence) O(n log2n) (best known worst case gap sequence)
  • Best-case performance: O(n log n) (most gap sequences) O(n log2n)  (best known worst case gap sequence)
  • Average performance: depends on gap sequence
  • Worst-case space complexity : О(n) total, O(1) auxiliary

Sell Sort Java Program

public class ShellSort {
public static void main(String[] args)
{
int[] items = { 2, 6, 3, 8, 4, 1, 5, 0 };
System.out.println("Before Shell Sorting :");
printArray(items);

//Perform shell sort
shellsort(items);

System.out.println("After Shell Sorting :");
printArray(items);
}
static void shellsort(int items[])
{
int n = items.length;

// Start with a big gap, then reduce the gap until 1
for (int gap = n/2; gap &gt; 0; gap /= 2)
{
//perform insertion sort for these gap size
//The first gap elements a[0..gap-1] are already
//in gapped order keep adding one more element
//until the entire array is gap sorted

for (int i = gap; i = gap &amp;&amp; items[j - gap] &gt; temp; j -= gap)
items[j] = items[j - gap];

// put temp in its correct  location
items[j] = temp;
}
}

}

static void printArray(int items[])
{
for (int item:items)
{
System.out.print(item + " ");
}
System.out.println();
}
}

Output

 


Before Shell Sorting :
2 6 3 8 4 1 5 0 
After Shell Sorting :
0 1 2 3 4 5 6 8 

[Sorting] Counting Sort program & Complexity (Big-O)

Counting sort also called an integer sorting algorithm. Counting sort algorithm is based on keys in a specific range. It counts the number of items for distinct key value, use these keys to determine position or indexing on the array and store respective counts for each key. Finally, sort values based on keys and make sequences the repetition of key based on counts.

Counting sort is suitable where variation in keys are is not significantly greater than the number of items. Its running time is linear as numbers of items(n)+difference between max and min key values.

Points to Remember

  • Data structure: Array
  • Worst-case performance: O(n+k), where k is the range of the non-negative key values.
  • Worst-case space complexity: O(n+k)

Advantage

  • Counting sort is a stable sort, where if two items have the same key, they should have the same relative position in the sorted output as they did in the input.

Disadvantage

  • Data range should be predefined, if not then addition loops required to get min and max value to get range.
  • Not much variation on key values otherwise will occupy unnecessary space in the array.

Steps for Counting Sort


For easily understand, consider the data in the range 0 to 9 for below example:
Input data: 2, 6, 3, 2, 8, 4, 8, 1, 5, 3, 1, 4, 0
1) Create an array of size 10 (index values 0-9) and store the count of each 
   unique item.
  Index:     0  1  2  3  4  5  6  7  8  9
  Count:     1  2  2  2  2  1  1  0  2  0

2) Execute loop for each index for array and check counts are more than zero. 
   repeat the index/key value until count reach to zero. Store these values in 
   previous array and increase index position by one. Now sorted array
 
  Index:     0  1  2  3  4  5  6  7  8  9 10   11 12
  Count:     0  1  1  2  2  3  3  4  4  5  6   8  8

Counting Sort Program

public class CountingSort {

public static void main(String[] args) {

//Assuming our key values are with in range 0 - 9
int[] items = { 2, 6, 3, 2, 8, 4, 8, 1, 5, 3, 1, 4, 0};
System.out.println("Before Counting Sorting :");
printArray(items);

//Perform counting sort sort
countingsort(items);

System.out.println("After Count Sorting :");
printArray(items);
}

private static void countingsort(int []items)
{
//create array of size 10 that will have index value as 0-9
//it will create array of size 10 and initialize
//each element with value 0
int []numbers=new int[10];
for(int key:items)
{
//for each match key, index position element
//increase count as 1
numbers[key]+=1;
}

//Now sort values based on keys and repeat
//this key value as per count
int i=0;
for(int key=0; key0)
{
for(int count=1;count&lt;=numbers[key];count++)
{
items[i++]=key;
}
}

}
}

static void printArray(int items[])
{
for (int item:items)
{
System.out.print(item + " ");
}
System.out.println();
}

}

Output


Before Counting Sorting :
2 6 3 2 8 4 8 1 5 3 1 4 0 
After Count Sorting :
0 1 1 2 2 3 3 4 4 5 6 8 8 

[Sorting] Heapsort Program and Complexity (Big-O)

Heapsort is a sorting algorithm based on a Binary Heap data structure. It’s a comparison-based sorting similar to Selection Sort where first find maximum item and place that maximum item at the end. Repeat the same steps for remaining items until all items sorted.

Points to Remember

  • Data structure: Array
  • Worst-case performance: O(n\log n)
  • Best-case performance : O(n\log n) (distinct keys) O(n) (equal keys)
  • Average performance: O(n\log n)
  • Worst-case space complexity: O(n) total O(1) auxiliary

See Also: Data Structure and Algorithms Complexity (Big-O)

Advantage

  • Heapsort is a more favorable in worst-case O(n log n) runtime.

Disadvantage

  • Heapsort slower in practice on most machines than a well-implemented quicksort.
  • Heapsort is not a stable sort but in-place algorithm.

Binary Heap Data Structure

Binary Heap is a type of Complete Binary Tree where items stored such a way like a parent node value is greater than the values of its child nodes. That is also called as Max heap. it can be represented in the form of a binary tree or array.

Binary Tree Representation in Array

To represent binary tree structure in the array, consider each array index as a node, where these index of nodes for a parent, left the child and right child follow these expression. In Binary tree for zero-based array ,the root node is stored at index 0; if i is the index of the current node, then

  • parent(i) = floor((i-1) / 2) , where floor map a real number to the smallest leading integer.
  • LeftChild(i) = 2*i + 1
  • RightChild(i) = 2*i + 2

Steps for Heap Sort

  1. Call the heapify() function on the array to make as Max Heap Binary Tree array where Maximum item on the first position.
  2. Swap the first item of the array with the final item. Consider the size of the array by decrease one. Call heapify() on the root of a binary tree.
  3. Repeat the above steps until the size of the unsorted heap is 1.

Note: The heapify() operation is run once, and is O(n) in performance. The swapping() function is O(log n) and is called n times. Therefore, the total performance of this heap sort algorithm is O(n + n log n) = O(n log n).

<h2>Heapsort Java Program</h2>
public class HeapSort {

public static void main(String []args)
{
int[] items = { 2, 6, 3, 8, 4, 1, 5, 0 };
System.out.println("Before Heap Sorting :");
printArray(items);

//Perform heap sort
heapsort(items);

System.out.println("After Heap Sorting :");
printArray(items);
}

public static void heapsort(int items[])
{
int itemCount = items.length;

// Build heap (rearrange array)
for (int i = itemCount / 2 - 1; i &gt;= 0; i--)
heapify(items, itemCount, i);

// One by one extract an element from heap
for (int i=itemCount-1; i&gt;=0; i--)
{
// Move max root item to end
int temp = items[0];
items[0] = items[i];
items[i] = temp;

// call max heapify on the reduced heap
heapify(items, i, 0);
}
}

/**
* Call the heapify() function on the array of decrease size to make as Max Heap Binary
* Tree array where Maximum item on first position or root.
*/
static void heapify(int items[], int itemCount, int i)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2

// If left child is larger than root
if (l  items[largest])
largest = l;

// If right child is larger than largest so far
if (r  items[largest])
largest = r;

// If largest is not root
if (largest != i)
{
int swap = items[i];
items[i] = items[largest];
items[largest] = swap;

// Recursively heapify the affected sub tree
heapify(items, itemCount, largest);
}
}

static void printArray(int items[])
{
for (int item:items)
{
System.out.print(item + " ");
}
System.out.println();
}
}

Output


Before Heap Sorting :
2 6 3 8 4 1 5 0 
After Heap Sorting :
0 1 2 3 4 5 6 8 

Data Structure and Algorithms Complexity (Big-O)

Big-O notation is a mathematical representation used to describe the complexity of a data structure and algorithm. There are two types of Complexity :

  1. Time Complexity: Its measure based on steps need to follow for an algorithm.
  2. Space Complexity: It measures the space required to perform an algorithm and data structure.

Data Structure and Algorithm Decision

Data structure and algorithm decisions are based on the complexity of size and operations need to perform on data. Some algorithms perform better on a small set of data while others perform better for big data sets for certain operations.

These days Space Complexity is not big concerns but the main performance of an algorithm measures based on time complexity. We can make the decision to choose an algorithm based on below performance criteria with respect to Complexity.

Complexity Performance
O(1) Excellent
O(log(n)) Good
O(n) Fair
O(n log(n)) Bad
O(n^2) Horrible
O(2^n) Horrible
O(n!) Horrible

This post almost covers data structure and algorithms space and time Big-O complexities. Here you can also see time complexities for types of operations like access, search, insertion, and deletion.

See also: 

Data Structure Space and Time Complexity

Data Structure Time Complexity Space Complexity
Average Worst
Access Search Insertion Deletion
Array Θ(1) Θ(n) Θ(n) Θ(n) O(n)
Stack Θ(n) Θ(n) Θ(1) Θ(1) O(n)
Queue Θ(n) Θ(n) Θ(1) Θ(1) O(n)
Singly-Linked List Θ(n) Θ(n) Θ(1) Θ(1) O(n)
Doubly-Linked List Θ(n) Θ(n) Θ(1) Θ(1) O(n)
Skip List Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n log(n))
Hash Table N/A Θ(1) Θ(1) Θ(1) O(n)
Binary Search Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)
Cartesian Tree N/A Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)
B-Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)
Red-Black Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)
Splay Tree N/A Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)
AVL Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)
KD Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)

Sorting Algorithms Space and Time Complexity

Algorithm Time Complexity Space Complexity
Best Average Worst Worst
Quick Sort Ω(n log(n)) Θ(n log(n)) O(n^2) O(log(n))
Merge Sort Ω(n log(n)) Θ(n log(n)) O(n log(n)) O(n)
Tim Sort Ω(n) Θ(n log(n)) O(n log(n)) O(n)
Heap Sort Ω(n log(n)) Θ(n log(n)) O(n log(n)) O(1)
Bubble Sort Ω(n) Θ(n^2) O(n^2) O(1)
Insertion Sort Ω(n) Θ(n^2) O(n^2) O(1)
Selection Sort Ω(n^2) Θ(n^2) O(n^2) O(1)
Tree Sort Ω(n log(n)) Θ(n log(n)) O(n^2) O(n)
Shell Sort Ω(n log(n)) Θ(n(log(n))^2) O(n(log(n))^2) O(1)
Bucket Sort Ω(n+k) Θ(n+k) O(n^2) O(n)
Radix Sort Ω(nk) Θ(nk) O(nk) O(n+k)
Counting Sort Ω(n+k) Θ(n+k) O(n+k) O(k)
Cube Sort Ω(n) Θ(n log(n)) O(n log(n)) O(n)

 

[Sorting] Selection Sort Program and Complexity (Big-O)

Selection sort is a simple sorting algorithm, it’s also known as in-place comparison sort. In selection sort algorithm, sorts an array of items by repeatedly finding the minimum item from unsorted part of array and move it at the beginning. This algorithm considers two sub arrays in a given array.

  1. The sub array of already sorted items.
  2. Remaining sub array unsorted items.

Points to remember

  • Data structure: Array
  • Worst-case performance : О(n2) comparisons and O(n)swaps
  • Best-case performance : O(n2) comparisons and O(n) Swaps
  • Average performance: О(n2) comparisons and O(n) Swaps
  • Worst-case space complexity :О(n) total, O(1) auxiliary

See Also : Data Structure and Algorithms Complexity (Big-O)

Advantage

  • Simple Implementation and efficient for small data set.
  • Efficient in  comparison to other Quadratic Sort (i.e O(n2)) like Bubble Sort or  Insertion Sort.
  • Efficient for data set that are already sorted. Time Complexity ( i.e O(n))
  • Not change relative order of elements which are already sorted. Space Complexity (i.e O(1))

Disadvantage

  • Selection sort is much less efficient on large lists in compare to algorithms such as quicksort, heapsort, or merge sort.

Selection Sort Steps

Here * marks the value set on particular iteration.

2 6 3 8 4 1 5 0
0* 6 3 8 4 1 5 2
0 1* 3 8 4 6 5 2
0 1 2* 8 4 6 5 3
0 1 2 3* 4 6 5 8
0 1 2 3 4* 6 5 8
0 1 2 3 4 5* 6 8
0 1 2 3 4 5 6* 8

Selection Sort with Loop

public class SelectionSort {
public static void main(String[] args) {
int[] items = { 2, 6, 3, 8, 4, 1, 5, 0 };
System.out.println("Before Selection Sorting :");
printArray(items);

// Perform selection sort
selectionSort(items);

System.out.println("After Selection Sorting :");
printArray(items);
}

static void selectionSort(int items[]) {

// select item one by one based on index
for (int i = 0; i &lt; items.length - 1; i++) {
// Find the minimum item in unsorted array
int min_idx = i;
for (int j = i + 1; j &lt; items.length; j++)
if (items[j] &lt; items[min_idx])
min_idx = j;

// Swap the found minimum selected item with
// the first selected item
int temp = items[min_idx];
items[min_idx] = items[i];
items[i] = temp;
}
}

static void printArray(int items[]) {
for (int item : items) {
System.out.print(item + " ");
}
System.out.println();
}
}

Output


Before Insertion Sorting :
2 6 3 8 4 1 5 0 
After Insertion Sorting :
0 1 2 3 4 5 6 8 

[Sorting] Insertion Sort Program and Complexity (Big-O)

Insertion sort is a simple sorting algorithm, which consumes one input item for each repetition, and grow a sorted output list. In every iteration, removes one item from input data, find the exact location in the sorted list and inserts it there. This process will repeat as long as no input items remain.

Points to remember

  • Data structure :  Array
  • Worst-case performance : О(n2) comparisons and swaps
  • Best-case performance : O(n) comparisons, O(1) swaps
  • Average performance: О(n2) comparisons and swaps
  • Worst-case space complexity : О(n) total, O(1) auxiliary

See Also: Data Structure and Algorithms Complexity (Big-O)

Advantage

  • Simple Implementation and efficient for small data set.
  • Not change relative order of elements which are already sorted
  • Efficient in comparison to other Quadratic Sort (i.e O(n2)) like Bubble Sort or Selection Sort.
  • Efficient for data set that are already sorted. Time Complexity( i.e O(n)).
  • Only required constant amount of memory space , as size of data set. Space
    Complexity (i.e O(1))

Disadvantage

  • Insertion sort is much less efficient on large lists in compare to algorithms such as quicksort, heapsort, or merge sort.

Insertion Sort Steps

Here * marks the value set on particular iteration.

2 6 3 8 4 1 5 0
2 6* 3 8 4 1 5 0
2 3* 6 8 4 1 5 0
2 3 6 8* 4 1 5 0
2 3 4* 6 8 1 5 0
1* 2 3 4 6 8 5 0
1 2 3 4 5* 6 8 0
0* 1 2 3 4 5 6 8

In following programs you will learn both the ways to implement Insertion Sort by For Loop and Recursion.

Insertion Sort with Loop

public class InsertionSort {
public static void main(String[] args) {
int[] items = { 2, 6, 3, 8, 4, 1, 5, 0 };
System.out.println("Before Sorting :");
printArrayTR(items);

//Perform insertion sort
insertionSort(items);

System.out.println("After Sorting :");
printArray(items);
}

static void insertionSort(int items[])
{
int n = items.length;
for (int i = 1; i = 0 &amp;&amp; items[j] &gt; key) {
items[j + 1] = items[j];
j = j - 1;
}
items[j + 1] = key;
printArrayTR(items);
}

}
static void printArray(int items[])
{
for (int item:items)
{
System.out.print(item + " ");
}
System.out.println();
}
}

Output


Before Insertion Sorting :
2 6 3 8 4 1 5 0 
After Insertion Sorting :
0 1 2 3 4 5 6 8 

Insertion Sort with Recursion

public class InsertionSortRecursion {
public static void main(String[] args) {
int[] items = { 2, 6, 3, 8, 4, 1, 5, 0 };
System.out.println("Before Insertion Sorting :");
printArray(items);

//Perform insertion sort
insertionSort(items,items.length);

System.out.println("After Insertion Sorting :");
printArray(items);
}

static void insertionSort(int items[],int n)
{
//base case or termination condition
if(n= 0 &amp;&amp; items[j] &gt; last)
{
items[j+1] = items[j];
j--;
}
items[j+1] = last;
}

static void printArray(int items[])
{
for (int item:items)
{
System.out.print(item + " ");
}
System.out.println();
}
}

Output


Before Insertion Sorting :
2 6 3 8 4 1 5 0 
After Insertion Sorting :
0 1 2 3 4 5 6 8 

[Java] Ways to Read Input from Keyboard/User/Console by Java Program

Java Support 4 Ways of  read  input from keyboard:

  • Scanner Class (In java.util package)
  • BufferReader and InputStreamReader (java.io package)
  • DataInputStream (Java.io package)
  • Console Class (Some IDE doesn’t support it For Example : Eclipse)

How Data Accepts from Keyboard ?

For accepting data from keyboard by console we need three objects:

  1. System.in
  2. InputStreamReader
  3. BufferedReader

The data is received in the form of bytes from the keyboard by System.in which is an InputStream object.Then the InputStreamReader reads bytes and decodes them into characters.Then finally BufferedReader object reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

 

InputStreamReader and BufferedReader are classes of java.io package.

Below Java Program showing all four ways of taking user input from console.

 

 

package program.common;

import java.io.BufferedReader;
import java.io.Console;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class UserInputWays {

public static void main(String[] args) {
Way1ByScanner();
System.out.println("=====================================================");
Way2ByBufferReader();
System.out.println("=====================================================");
Way3ByDataStream();
System.out.println("=====================================================");
Way4ByConsole();
System.out.println("=====================================================");
}

private static void Way1ByScanner() {
System.out.println("Way 1 : By Scanner Class");
Scanner scan = new Scanner(System.in);

System.out.println("Enter a text string");
String s = scan.nextLine();
System.out.println("You entered text string " + s);

System.out.println("Enter an integer value");
int a = scan.nextInt();
System.out.println("You entered integer value " + a);

System.out.println("Enter a float value");
float b = scan.nextFloat();
System.out.println("You entered float value " + b);

}

private static void Way2ByBufferReader() {
System.out.println("Way 2 : By BufferReader and InputStreamReader");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a text string");
String s = br.readLine();
System.out.println("You entered text string " + s);

System.out.println("Enter an integer value");
int a = Integer.parseInt(br.readLine());
System.out.println("You entered integer value " + a);

System.out.println("Enter a float value");
float b = Float.parseFloat(br.readLine());
System.out.println("You entered float value " + b);

} catch (IOException ex) {
ex.printStackTrace();
}
}

private static void Way3ByDataStream() {
System.out.println("Way 3 : By DataStream");
try {
DataInputStream dis = new DataInputStream(System.in);

System.out.println("Enter a text string");
String s = dis.readLine();
System.out.println("You entered text string " + s);

System.out.println("Enter an integer value");
int a = dis.readInt();
System.out.println("You entered integer value " + a);

System.out.println("Enter a float value");
float b = dis.readFloat();
System.out.println("You entered float value " + b);
} catch (IOException ex) {
ex.printStackTrace();
}
}

/**
* Eclipse doesn't support Console Class to test that use command prompt
*/
private static void Way4ByConsole() {
System.out.println("Way 4 : By Console Class");
try
{
Console console = System.console();

System.out.println("Enter a text string");
String s = console.readLine();
System.out.println("You entered text string " + s);

System.out.println("Enter an integer value");
int a = Integer.parseInt(console.readLine());
System.out.println("You entered integer value " + a);

System.out.println("Enter a float value");
float b = Float.parseFloat(console.readLine());
System.out.println("You entered float value " + b);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

}

Output

Way 1 : By Scanner Class
Enter a text string
saurabh Gupta
You entered text string saurabh Gupta
Enter an integer value
35
You entered integer value 35
Enter a float value
80.2
You entered float value 80.2
=====================================================
Way 2 : By BufferReader and InputStreamReader
Enter a text string
Saurabh Gupta
You entered text string Saurabh Gupta
Enter an integer value
35
You entered integer value 35
Enter a float value
80.2
You entered float value 80.2
=====================================================
Way 3 : By DataStream
Enter a text string
Saurabh Gupta
You entered text string Saurabh Gupta
Enter an integer value
35
You entered integer value 859114762
Enter a float value
80.2
You entered float value 4.2004693E-5
=====================================================
Way 4 : By Console Class
Enter a text string
=====================================================
java.lang.NullPointerException
at program.common.UserInputWays.Way4ByConsole(UserInputWays.java:91)
at program.common.UserInputWays.main(UserInputWays.java:19)

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Floyd Triangle Java Program

This is Java Program to print Floyd triangle of continuous numbers based on inserted users numbers of rows.

import java.util.Scanner;

class FloydTriangle
{
public static void main(String args[])
{
int n, num = 1, c, d;
Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows of floyd's triangle you want");
n = in.nextInt();

System.out.println("Floyd's triangle :-");

for ( c = 1 ; c &lt;= n ; c++ )
{
for ( d = 1 ; d &lt;= c ; d++ )
{
System.out.print(num+" ");
num++;
}

System.out.println();
}
}
}

output

Enter the number of rows of floyd's triangle you want
7
Floyd's triangle :-
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

More

For more Algorithms and Java Programing Test questions and sample code follow below links

[Java] Multiplication Table Java Program

This Java program is for print Multiplication table of Input Number.

import java.util.Scanner;

class MultiplicationTable
{
public static void main(String args[])
{
int n, c;
System.out.println("Enter an integer value to display it's multiplication table");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println("Multiplication table of "+n+" is :-");

for ( c = 1 ; c &lt;= 10 ; c++ )
System.out.println(n+"*"+c+" = "+(n*c));
}
}

Output

Enter an integer value to display it's multiplication table

13
Multiplication table of 13 is :-
13*1 = 13
13*2 = 26
13*3 = 39
13*4 = 52
13*5 = 65
13*6 = 78
13*7 = 91
13*8 = 104
13*9 = 117
13*10 = 130

More

For more Algorithms and Java Programing Test questions and sample code follow below links

 

[Java] Largest of Three Numbers Java Program

This java program is to easily find out largest number in three integers values. But that is not optimize way if numbers are more than that better follow other algorithms.

lass LargestOfThreeNumbers {
public static void main(String args[]) {
int x, y, z;

Scanner in = new Scanner(System.in);
System.out.println("Please Enter First integer");
x = in.nextInt();
System.out.println("Please Enter Second integer");
y = in.nextInt();
System.out.println("Please Enter Third integer");
z = in.nextInt();

if (x &gt; y &amp;&amp; x &gt; z)
System.out.println("First number is largest.");
else if (y &gt; x &amp;&amp; y &gt; z)
System.out.println("Second number is largest.");
else if (z &gt; x &amp;&amp; z &gt; y)
System.out.println("Third number is largest.");
else
System.out.println("Entered numbers are not distinct.");
}
}

Output

Please Enter First integer
10
Please Enter Second integer
20
Please Enter Third integer
5
Second number is largest.

More

For more Algorithms and Java Programing Test questions and sample code follow below links

[Java] Palindrome Java Program

Palindrome Definition

“A String is palindrome if it remains unchanged when reversed.”

For Example : String “dad” is a palindrome as reverse of “dad” is “dad” whereas
“program” is not a palindrome. Some other palindrome strings are “nitin”,”mom”, “madam”, “abcba” etc.

Below is simple Java program to check input String is Palindrom or not.

class Palindrome1 {
public static void main(String args[]) {
String original, reverse = "";
Scanner in = new Scanner(System.in);

System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();

int length = original.length();

for (int i = length - 1; i &gt;= 0; i--)
reverse = reverse + original.charAt(i);

if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");

}
}

Output

Enter a string to check if it is a palindrome
nitin
Entered string is a palindrome.

Enter a string to check if it is a palindrome
Saurabh
Entered string is not a palindrome.

In above program you find out very simple way to check input string is palindrome but in below program you will see to check palindrome string with minimum number of operations because here dividing text in half size and compare with rest of part of String.

import java.util.*;

class Palindrome2
{
public static void main(String args[])
{
String inputString;
Scanner in = new Scanner(System.in);

System.out.println("Enter a string to check if it is a palindrome");
inputString = in.nextLine();

int length  = inputString.length();
int i, begin, end, middle;

begin  = 0;
end    = length - 1;
middle = (begin + end)/2;

for (i = begin; i &lt;= middle; i++) {
if (inputString.charAt(begin) == inputString.charAt(end)) {
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
System.out.println("Entered string is a palindrome.");
}
else {
System.out.println("Entered string is not a palindrome.");
}
}
}

Output

Enter a string to check if it is a palindrome
nitin
Entered string is a palindrome.

Enter a string to check if it is a palindrome
Saurabh
Entered string is not a palindrome.

More

For more Algorithms and Java Programing Test questions and sample code follow below links

[Java] Prime Numbers Java program

Prime Number Definition

                 “A whole number greater than 1 that is divisible only by itself and 1”.
A prime number will always have factors as 1 and itself. A factor is a whole numbers that can be divided evenly into another number. If Number is having more than two factors are called composite numbers.
The number 1 is neither prime nor a composite Number.
Smallest prime number is 2 and others are in sequence as 2,3,5,7,11,13,17,19,13,29  etc…

Benefit

  • prime numbers are very useful in cryptography.
  • The mathematicians used prime numbers to develop new areas of mathematics, like number theory and knot theory, which developers use today.
This java program prints  number of prime numbers as required from the user.
import java.util.*;

class PrimeNumbers
{
public static void main(String args[])
{
int n, status = 1, num = 3;

Scanner in = new Scanner(System.in);
System.out.println("Enter the number of prime numbers you want");
n = in.nextInt();

if (n &amp;gt;= 1)
{
System.out.println("First "+n+" prime numbers are :-");
System.out.println(2);
}

for ( int count = 2 ; count &amp;lt;=n ;  )
{
for ( int j = 2 ; j &amp;lt;= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
count++;
}
status = 1;
num++;
}
}
}

Output

Enter the number of prime numbers you want
5
First 5 prime numbers are :-
2
3
5
7
11
Enter the number of prime numbers you want

10
First 10 prime numbers are :-
2
3
5
7
11
13
17
19
23
29

More

For more Algorithms and Java Programing Test questions and sample code follow below links

[Java] Odd and Even Java Program

This java program finds if a number is odd or even.

If the number is divisible by 2 then it will be even, otherwise it is odd. We use Java modulus operator to find remainder in our program.

class OddOrEvenNumber{
	public static void main(String args[]) {
		int x;
		System.out.println("Enter an integer value to check if it is odd or even ");
		Scanner in = new Scanner(System.in);
		x = in.nextInt();

		if (x % 2 == 0)
			System.out.println("You entered an even number.");
		else
			System.out.println("You entered an odd number.");
	}
}

Output

Enter an integer value to check if it is odd or even
16
You entered an even number.

Enter an integer value to check if it is odd or even
125
You entered an odd number.

More

For more Algorithms and Java Programing Test questions and sample code follow below links

[Java] How to Reverse Number by Java Program?

Here in below program logic you will see how can be reverse number by using multiplication, reminder and division operations.

In this  below program follow steps for reverse number:

  1. Reverse number initialize with zero.
  2. Run loop till number of digits in insert number.
  3. Take reminder of number by mod 10.
  4. Add this reminder value with reverse number .
  5. Multiply this reverse number with 10 .
  6. Divide insert number by 10 and steps 2 to 6 repeat continuously.
import java.util.Scanner;

class ReverseNumber
{
public static void main(String args[])
{
int n, reverse = 0;

System.out.println("Enter the integer number to reverse");
Scanner in = new Scanner(System.in);
n = in.nextInt();

while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}

System.out.println("Reverse of entered integer number is "+reverse);
}
}

Output

Enter the integer number to reverse
12345
Reverse of entered integer number is 54321

Enter the integer number to reverse

54535251
Reverse of entered integer number is 15253545

More

For more Algorithms and Java Programing Test questions and sample code follow below links

[Java] How to Prints Alphabets by Java Loops

Here you will see, How to prints Alphabets through Java all loops (for, While and do while). In these loops we are just increments char value and characters are increment continuously.

public class PrintAlphabets {

public static void main(String[] args) {
// By for Loop
char ch;
for (ch = 'a'; ch &lt;= 'z'; ch++) {
System.out.print(ch + " ");
}
System.out.println();

// By While loop
char c = 'a';

while (c &lt;= 'z') {
System.out.print(c + " ");
c++;
}
System.out.println();

// By do while loop
c = 'A';

do {
System.out.print(c + " ");
c++;
} while (c &lt;= 'Z');
}

}

Output

a b c d e f g h i j k l m n o p q r s t u v w x y z
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

More

For more Algorithms and Java Programing Test questions and sample code follow below links

 

[Java] Factorial of a Number by Java Program

The Factorial of number is denoted by n! , is the product/multiplication of all positive integers less than or equal to n.

Where n is always a non-negative number and The value of 0! is 1, according to the convention for an empty product.

Example :

0!=1=1
1!=1=1
5!=5 * 4 * 3 * 2 * 1=120
12!=12 * 11 * 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1=479001600

Below are examples to calculate factorial of  a Number. I have consider all the cases like calculation of big factorial number by loop and also through recursion.

Factorial of a Number by using Java code loop.

class Factorial {
public static void main(String args[]) {
int n, c, fact = 1;

System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);

n = in.nextInt();

if (n &lt; 0)
System.out.println("Number should be non-negative.");
else {
for (c = 1; c &lt;= n; c++)
fact = fact * c;

System.out.println("Factorial of " + n + " is = " + fact);
}
}
}

Factorial of a Big Integer Number by using loop

If calculation of number is too big which cross the Integer limit then use BigInteger instead if Integer.

class Factorial {
public static void main(String args[]) {
int n, c;
BigInteger inc = new BigInteger("1");
BigInteger fact = new BigInteger("1");

Scanner input = new Scanner(System.in);

System.out.println("Input an integer");
n = input.nextInt();

for (c = 1; c &lt;= n; c++) {
fact = fact.multiply(inc);
inc = inc.add(BigInteger.ONE);
}

System.out.println(n + "! = " + fact);
}
}

Factorial of Integer Number by using Java Recursion.

import java.util.Scanner;

public class FactorialByRecursion {

public static void main(String[] args) {
int n;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);

n = in.nextInt();

if (n &lt; 0)
System.out.println("Number should be non-negative.");
else {
System.out.println("Factorial of " + n + " is = " + factorial(n));
}

}

private static int factorial(int num)
{
//Recursion Terminating condition if 0 terminate with value 1
if(num==0)
return 1;
else
return num*factorial(num-1);
}

}

More Info

For more Algorithms and Java Programing Test questions and sample code follow below links

 

Armstrong Number JAVA Program

Armstrong number is a number which is equal to sum of digits raise to the power total number of digits in the number.

Example :

33+ 73 + 13 = 371

14 + 64 + 34 + 44=1634

Below is JAVA program to check Armstrong Number.

import java.util.Scanner;

class ArmstrongNumber {
public static void main(String args[]) {
int n, sum = 0, temp, remainder, digits = 0;

Scanner in = new Scanner(System.in);
System.out.println("Input a number to check if it is an Armstrong number");
n = in.nextInt();

temp = n;

// Count number of digits

while (temp != 0) {
digits++;
temp = temp / 10;
}

temp = n;

while (temp != 0) {
remainder = temp % 10;
sum = sum + power(remainder, digits);
temp = temp / 10;
}

if (n == sum)
System.out.println(n + " is an Armstrong number.");
else
System.out.println(n + " is not an Armstrong number.");
}

static int power(int n, int r) {
int c, p = 1;

for (c = 1; c &lt;= r; c++)
p = p * n;

return p;
}
}

More Info

For more Algorithms and Java Programing Test questions and sample code follow below links

[Sorting] Bubble Sort/ Sinking Sort Java Program

Bubble Sort also called Sinking Sort is a comparison sort algorithm where smaller or larger “bubble” elements move to top.

Complexity

Complexity of bubble sort is O(n2) in both average and worst case while O(n) in best case when elements are already sorted. Where n is number of elements.

Drawback

It will not be efficient in the case of a reverse-ordered collection or number of elements are high.

import java.util.Scanner;

public class BubbleSort {
public static void main(String []args) {
int n, c, d, swap;
//For User Input
Scanner in = new Scanner(System.in);

System.out.println("Input number of integers to sort");
n = in.nextInt();

int array[] = new int[n];

System.out.println("Enter " + n + " integers");

for (c = 0; c &lt; n; c++)
array = in.nextInt();

for (c = 0; c &lt; ( n - 1 ); c++) {
for (d = 0; d &lt; n - c - 1; d++) {
/* In case of descending order use &lt; */ if (array[d] &gt; array[d+1])
{
swap       = array[d];
array[d]   = array[d+1];
array[d+1] = swap;
}
}
}
System.out.println("Sorted list of numbers");

for (c = 0; c &lt; n; c++)
System.out.println(array);
}
}

 

More

For more Algorithms and Java Programing Test questions and sample code follow below links

 

How to Convert JSON to Java Object and Java Object to JSON?

In below java codes consider both the cases from JSON to Java Object and Java Object to JSON by ObjectMapper by Jacson API’s

I have given generic method for both the cases as convertJavaObjectToJSON and convertJSONToJavaObject.

Pre-Requisite : Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
&lt;version&gt;2.8.5&lt;/version&gt;
&lt;/dependency&gt;

JAVA and JSON Conversion Example:

Below is complete example for conversion of both the cases.

ObjectMapper.readValue() :Convert JSON String to Java Object

ObjectMapper.writeValue() : Convert JAVA Object to JSON

package test.facingissesonit.json.jacson;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonAndJavaObjectConversion {

public static void main(String[] args) {
System.out.println(&quot;=================Convert Student Java Object to JSON==============&quot;);
// convert Object to json string
Student student = sampleStudentObject();

String studentStr = convertJavaObjectToJSON(student);
System.out.println(&quot;Student JSON Data \n&quot; + studentStr);
System.out.println(&quot;=================Convert JSON DATA  to Student JAVA Object==============&quot;);
Object object = convertJSONToJavaObject(studentStr, Student.class);
if (object != null &amp;&amp; object instanceof Student) {
System.out.println(&quot;Student Object\n&quot; + (Student) object);
}

}
//Generic Method to convert JSON object to Java Object
public static Object convertJSONToJavaObject(String strJsonData, Class className) {
try {
// ObjectMapper new instance
ObjectMapper objectMapper = new ObjectMapper();
// //convert json data from file text to object
return objectMapper.readValue(strJsonData, className);
} catch (JsonMappingException ex) {
ex.printStackTrace();
} catch (JsonGenerationException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
//Generic Method to convert Java object to JSON
public static String convertJavaObjectToJSON(Object javaObject) {
StringWriter jsonStr = null;
try {

// ObjectMapper new instance
ObjectMapper objectMapper = new ObjectMapper();
// configure Object mapper for pretty print
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

// writing to console, can write to any output stream such as file
jsonStr = new StringWriter();
objectMapper.writeValue(jsonStr, javaObject);

} catch (JsonMappingException ex) {
ex.printStackTrace();
} catch (JsonGenerationException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return jsonStr.toString();
}

public static Student sampleStudentObject() {

Student student = new Student();
student.setRollNumber(11);
student.setFirstName(&quot;Saurabh&quot;);
student.setLastName(&quot;Gupta&quot;);
student.setPhoneNumbers(new long[] { 2233445566L, 3344556677L });

Address add = new Address();
add.setAddressLine(&quot;Lake Union Hill Way&quot;);
add.setCity(&quot;Atlanta&quot;);
add.setState(&quot;GA&quot;);
add.setZipCode(50005);
student.setAddress(add);

List&lt;String&gt; cities = new ArrayList&lt;String&gt;();
cities.add(&quot;Dallas&quot;);
cities.add(&quot;San Antonio&quot;);
cities.add(&quot;Irving&quot;);
student.setCities(cities);

Map&lt;String, String&gt; props = new HashMap&lt;String, String&gt;();
props.put(&quot;age&quot;, &quot;34 years&quot;);
props.put(&quot;interst&quot;, &quot;Math&quot;);
props.put(&quot;play&quot;, &quot;Badminton&quot;);

student.setProperties(props);

return student;
}

}

Model Classes :

package test.facingissesonit.json.jacson;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Student {
private int rollNumber;
private String firstName;
private String lastName;
private boolean permanent;
private Address address;
private long[] phoneNumbers;
private List&lt;String&gt; cities;
private Map&lt;String, String&gt; properties;
@Override
public String toString()
{
StringBuffer sb=new StringBuffer();
sb.append(&quot;==============Student Information================\n&quot;);
sb.append(&quot;rollNumber=&quot;).append(rollNumber).append(&quot;\n&quot;);
sb.append(&quot;firstName=&quot;).append(firstName).append(&quot;\n&quot;);
sb.append(&quot;lastName=&quot;).append(lastName).append(&quot;\n&quot;);
sb.append(&quot;permanent=&quot;).append(permanent).append(&quot;\n&quot;);
sb.append(&quot;adress=&quot;).append(address).append(&quot;\n&quot;);
sb.append(&quot;phoneNumbers=&quot;).append(Arrays.toString(phoneNumbers)).append(&quot;\n&quot;);
sb.append(&quot;cities=&quot;).append(Arrays.toString(cities.toArray(new String[cities.size()]))).append(&quot;\n&quot;);
sb.append(&quot;properties=&quot;).append(properties).append(&quot;\n&quot;);
return sb.toString();
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isPermanent() {
return permanent;
}
public void setPermanent(boolean permanent) {
this.permanent = permanent;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public long[] getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(long[] phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public List&lt;String&gt; getCities() {
return cities;
}
public void setCities(List&lt;String&gt; cities) {
this.cities = cities;
}
public Map&lt;String, String&gt; getProperties() {
return properties;
}
public void setProperties(Map&lt;String, String&gt; properties) {
this.properties = properties;
}

}

package test.facingissesonit.json.jacson;

public class Address {
private String addressLine;
private String city;
private String state;
private int zipCode;
@Override
public String toString()
{
StringBuffer sb=new StringBuffer();
sb.append(&quot;AddressLine=&quot;).append(addressLine).append(&quot;\n&quot;);
sb.append(&quot;city=&quot;).append(city).append(&quot;\n&quot;);
sb.append(&quot;state=&quot;).append(state).append(&quot;\n&quot;);
sb.append(&quot;zipCode=&quot;).append(zipCode).append(&quot;\n&quot;);
return sb.toString();
}
public String getAddressLine() {
return addressLine;
}
public void setAddressLine(String addressLine) {
this.addressLine = addressLine;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getZipCode() {
return zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
}

Output:

=================Convert Student Java Object to JSON==============
Student JSON Data
{
&quot;rollNumber&quot; : 11,
&quot;firstName&quot; : &quot;Saurabh&quot;,
&quot;lastName&quot; : &quot;Gupta&quot;,
&quot;permanent&quot; : false,
&quot;address&quot; : {
&quot;addressLine&quot; : &quot;Lake Union Hill Way&quot;,
&quot;city&quot; : &quot;Atlanta&quot;,
&quot;state&quot; : &quot;GA&quot;,
&quot;zipCode&quot; : 50005
},
&quot;phoneNumbers&quot; : [ 2233445566, 3344556677 ],
&quot;cities&quot; : [ &quot;Dallas&quot;, &quot;San Antonio&quot;, &quot;Irving&quot; ],
&quot;properties&quot; : {
&quot;play&quot; : &quot;Badminton&quot;,
&quot;interst&quot; : &quot;Math&quot;,
&quot;age&quot; : &quot;34 years&quot;
}
}
=================Convert JSON DATA  to Student JAVA Object==============
Student Object
==============Student Information================
rollNumber=11
firstName=Saurabh
lastName=Gupta
permanent=false
adress=AddressLine=Lake Union Hill Way
city=Atlanta
state=GA
zipCode=50005

phoneNumbers=[2233445566, 3344556677]
cities=[Dallas, San Antonio, Irving]
properties={play=Badminton, interst=Math, age=34 years}

More Sample Code

For more java and JDBC codes follow below links

Java, How to convert List to Arrays and Array to ArrayList

In our day to day programming sometime use this conversion by using iteration but there is another way by using Java API’s as below.

ArrayList to Arrays

List provide toArray() method to convert list elements in Arrays.

List&lt;T&gt; list = new ArrayList&lt;T&gt;();
T[]arr=list.toArray(new T[list.size]);

Example :

import java.util.ArrayList;
import java.util.List;

public class ConvertArrayListToArray {

public static void main(String[] args) {
List&lt;String&gt; list = new ArrayList&lt;String&gt;();
list.add(&quot;Georgia&quot;);
list.add(&quot;Texas&quot;);
list.add(&quot;Newyork&quot;);
list.add(&quot;Okhlama&quot;);
String [] states = list.toArray(new String[list.size()]);
}

}

Arrays to ArrayList

Arrays class provide to asList() method to convert Array to immutable List So if you need to modify anything in List you will get java.lang.UnsupportedOperationException.

If you want to modification after convert to List then create with new ArrayList as below.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ConvertArrayToArrayList {

public static void main(String[] args) {
String [] states= {&quot;Georgia&quot;,&quot;Texas&quot;,&quot;New York&quot;, &quot;Okhlama&quot;};
//Convert Array to immutable List
List&lt;String&gt; stateList= Arrays.asList(states);
try
{
stateList.add(&quot;North Carolina&quot;);
}
catch(UnsupportedOperationException ex)
{
ex.printStackTrace();
}

//Convert Array to mutable List
stateList=new ArrayList&lt;String&gt;(Arrays.asList(states));
stateList.add(&quot;North Carolina&quot;);
System.out.println(stateList.get(4));
}

}

In above example I have considered both cases for Immutable and Mutable.

More Sample Code

For more java and JDBC codes follow below links