How to print Hollow Square Pattern in Java - Step by Step Examples



How to print Hollow Square Pattern in Java ?

Answer

To print a Hollow Square Pattern in Java, we use nested loops. The outer loop controls the rows, and the inner loops control the columns and the conditions for printing the hollow square pattern.



✐ Examples

1 Hollow Square Pattern

In this example,

  1. We define a function printHollowSquare that takes the size of the square n as a parameter.
  2. We use two nested for loops to iterate over rows and columns.
  3. Within the loops, we check if we are at the first or last row or column, or if the current position is on the border of the square. If so, we print a star (*); otherwise, we print a space.

Java Program

// Hollow Square Pattern
public class Main {
    public static void printHollowSquare(int n) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || i == n - 1 || j == 0 || j == n - 1)
                    System.out.print("*");
                else
                    System.out.print(" ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        printHollowSquare(5);
    }
}

Output

*****
*   *
*   *
*   *
*****

Summary

In this tutorial, we learned How to print Hollow Square Pattern in Java language with well detailed examples.




More Java Pattern Printing Tutorials

  1. How to print Left Half Pyramid Pattern in Java ?
  2. How to print Right Half Pyramid Pattern in Java ?
  3. How to print Pyramid Pattern in Java ?
  4. How to print Rhombus Pattern in Java ?
  5. How to print Diamond Pattern in Java ?
  6. How to print Hour Glass Pattern in Java ?
  7. How to print Hollow Square Pattern in Java ?
  8. How to print Hollow Pyramid Pattern in Java ?
  9. How to print Hollow Inverted Pyramid Pattern in Java ?
  10. How to print Hollow Diamond Pattern in Java ?
  11. How to print Floyd's Trianlge Pattern in Java ?
  12. How to print Pascal's Triangle Pattern in Java ?