Java Program to Print Hollow Square Pattern
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
How to Think About It
Algorithm
Code
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(); } } }
Dry Run
Let's trace n=3 through the code
Start outer loop i=1 (first row)
Check columns j=1 to 3; all positions are border, print '*' for each.
Outer loop i=2 (middle row)
For j=1 and j=3 (first and last column), print '*'; for j=2 print space.
Outer loop i=3 (last row)
All columns are border, print '*' for each.
| i | j | Condition (border?) | Printed |
|---|---|---|---|
| 1 | 1 | true | * |
| 1 | 2 | true | * |
| 1 | 3 | true | * |
| 2 | 1 | true | * |
| 2 | 2 | false | |
| 2 | 3 | true | * |
| 3 | 1 | true | * |
| 3 | 2 | true | * |
| 3 | 3 | true | * |
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
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++; } } }
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); } } }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops | O(n^2) | O(1) | Simple and clear code |
| While loops | O(n^2) | O(1) | When you prefer while syntax |
| Function-based | O(n^2) | O(1) | Cleaner code and reusability |