Hollow Square of Stars

This program prints a hollow square of stars.

Problem Statement

Write a Java program that prints a hollow square of stars with 5 rows.

Source Code

1 public class HollowSquareStars {
2 public static void main(String[] args) {
3 int n = 5;
4 for(int i=1; i<=n; i++) {
5 for(int j=1; j<=n; j++) {
6 if(i==1 || i==n || j==1 || j==n) {
7 System.out.print("* ");
8 } else {
9 System.out.print(" ");
10 }
11 }
12 System.out.println();
13 }
14 }
15 }

Program Output

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

Explanation

Both loops control the rows and columns, and the condition i==1 || i==n || j==1 || j==n prints stars only at the borders while the else branch prints spaces, creating a hollow effect that demonstrates conditional logic inside loops.

Quick Links to Explore