Hollow Diamond Pattern in Java

star pattern 11

In this tutorial, we will write a program to print a hollow diamond star pattern in java. We will go through two examples. Before that, you may go through the following topic in java.

The program takes a user input for the number of rows for the hollow pattern using the Scanner class. We will use a for loop to iterate and print the pattern.

The user can give the input number as they wish and get the hollow diamond star pattern according to their input provided.


Java Program To Display Hollow Diamond Star Pattern

import java.util.Scanner;

public class Main
{
  public static void main(String[] args)
  {
    int rows, i, j;
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter the number of rows: ");
    rows = sc.nextInt();

    //Upper part of diamond
    for (i = 1; i <= rows; i++)
    {
      for (j = rows; j > i; j--)
        System.out.print(" ");

      System.out.print("*");

      for (j = 1; j < (i - 1) *2; j++)
        System.out.print(" ");

      if (i == 1)
        System.out.print("\n");
      else
        System.out.print("*\n");
    }

    //lower part of diamond
    for (i = rows - 1; i >= 1; i--)
    {
      for (j = rows; j > i; j--)
        System.out.print(" ");

      System.out.print("*");

      for (j = 1; j < (i - 1) *2; j++)
        System.out.print(" ");

      if (i == 1)
        System.out.print("\n");
      else
        System.out.print("*\n");
    }
  }
}

Output:

Hollow Diamond Pattern in Java

Print Hollow Diamond Pattern using Star in Java using while loop

The program below takes the rows input from the user as the above program did but here we will produce a hollow diamond pattern using a while loop instead of for loop.

import java.util.Scanner;

public class Main
{
  public static void main(String[] args)
  {
    int rows, i, j;
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter the number of rows: ");
    rows = sc.nextInt();

    //Upper part of diamond
    i = 1;
    while (i <= rows)
    {
      j = rows;
      while (j > i)
      {
        System.out.print(" ");
        j--;
      }
      System.out.print("*");

      j = 1;
      while (j < (i - 1) *2)
      {
        System.out.print(" ");
        j++;
      }

      if (i == 1)
        System.out.print("\n");
      else
        System.out.print("*\n");

      i++;
    }

    //lower part of diamond
    i = rows - 1;
    while (i >= 1)
    {
      j = rows;
      while (j > i)
      {
        System.out.print(" ");
        j--;
      }

      System.out.print("*");

      j = 1;
      while (j < (i - 1) *2)
      {
        System.out.print(" ");
        j++;
      }

      if (i == 1)
        System.out.print("\n");
      else
        System.out.print("*\n");

      i--;
    }
  }
}

The above program with a while loop will produce the same result as the for loop has produced. The only difference is we used while instead of for loop.