0
0
JavaProgramBeginner · 2 min read

Java Program to Print Hollow Square Pattern

You can print a hollow square pattern in Java using nested for loops and printing stars * on the borders and spaces inside, like this: for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (i == 1 || i == n || j == 1 || j == n) System.out.print("*"); else System.out.print(" "); } System.out.println(); }.
📋

Examples

Inputn = 3
Output*** * * ***
Inputn = 5
Output***** * * * * * * *****
Inputn = 1
Output*
🧠

How to Think About It

To print a hollow square, think of a grid with rows and columns. Print stars on the first and last rows and columns to form the border. For all other positions inside, print spaces to keep it hollow.
📐

Algorithm

1
Get the size n of the square.
2
Loop from 1 to n for each row.
3
Inside each row, loop from 1 to n for each column.
4
If the current position is on the first or last row, or first or last column, print a star.
5
Otherwise, print a space.
6
After each row, move to the next line.
💻

Code

java
public class HollowSquare {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (i == 1 || i == n || j == 1 || j == n) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}
Output
***** * * * * * * *****
🔍

Dry Run

Let's trace n=3 through the code

1

Start outer loop i=1 (first row)

Check columns j=1 to 3; all positions are border, print '*' for each.

2

Outer loop i=2 (middle row)

For j=1 and j=3 (first and last column), print '*'; for j=2 print space.

3

Outer loop i=3 (last row)

All columns are border, print '*' for each.

ijCondition (border?)Printed
11true*
12true*
13true*
21true*
22false
23true*
31true*
32true*
33true*
💡

Why This Works

Step 1: Outer and inner loops

The outer loop runs through each row, and the inner loop runs through each column, covering every position in the square.

Step 2: Border condition

We print stars only if the current position is on the first or last row or column, which forms the square's border.

Step 3: Printing spaces inside

For positions not on the border, we print spaces to keep the square hollow.

🔄

Alternative Approaches

Using while loops
java
public class HollowSquare {
    public static void main(String[] args) {
        int n = 5;
        int i = 1;
        while (i <= n) {
            int j = 1;
            while (j <= n) {
                if (i == 1 || i == n || j == 1 || j == n) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
                j++;
            }
            System.out.println();
            i++;
        }
    }
}
Uses while loops instead of for loops; functionally same but slightly more verbose.
Using a function to print each line
java
public class HollowSquare {
    public static void printLine(int n, int row) {
        for (int col = 1; col <= n; col++) {
            if (row == 1 || row == n || col == 1 || col == n) {
                System.out.print("*");
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            printLine(n, i);
        }
    }
}
Separates printing logic into a function for cleaner main method and reusability.

Complexity: O(n^2) time, O(1) space

Time Complexity

The program uses two nested loops each running n times, resulting in O(n^2) time to print all positions.

Space Complexity

Only a few variables are used; no extra space proportional to n, so space complexity is O(1).

Which Approach is Fastest?

All approaches use nested loops and have similar time and space complexity; differences are mainly in code style.

ApproachTimeSpaceBest For
For loopsO(n^2)O(1)Simple and clear code
While loopsO(n^2)O(1)When you prefer while syntax
Function-basedO(n^2)O(1)Cleaner code and reusability
💡
Use nested loops and print stars only on the edges to create a hollow square.
⚠️
Beginners often print stars everywhere, forgetting to leave spaces inside for the hollow effect.