Write a Java program that prints a hollow square pattern.
This Java program prints a hollow square pattern using * symbols. The hollow square consists of a border of stars, while the inside is filled with spaces.
class Main {
public static void main(String[] args) {
final int SQUARE_SIZE = 5; // Size of the square
// Loop through rows
for (int row = 1; row <= SQUARE_SIZE; row++) {
// Loop through columns
for (int column = 1; column <= SQUARE_SIZE; column++) {
// Print "*" on the border, otherwise print space
if (row == 1 || row == SQUARE_SIZE || column == 1 || column == SQUARE_SIZE) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
// Move to the next line after each row
System.out.println();
}
}
}
Output:
* * * * *
* *
* *
* *
* * * * *
Code Breakdown
final int SQUARE_SIZE = 5;
Defines the size of the square. For example, SQUARE_SIZE = 5 creates a 5×5 square.
Outer Loop (for (int row = 1; row <= SQUARE_SIZE; row++))
Controls the rows of the square.
Runs from 1 to SQUARE_SIZE (inclusive).
Inner Loop (for (int column = 1; column <= SQUARE_SIZE; column++))
Controls the columns of each row.
Condition (if (row == 1 || row == SQUARE_SIZE || column == 1 || column == SQUARE_SIZE))
Prints * only for the borders:
row == 1: Top border.
row == SQUARE_SIZE: Bottom border.
column == 1: Left border.
column == SQUARE_SIZE: Right border.
For all other cells, it prints spaces (” “).
System.out.println();
Moves to the next line after printing all columns in a row.
Key Points
Customizations:
To change the size of the square, modify SQUARE_SIZE.
Replace “* ” with any other character to change the border design.
Logic for Hollow Structure:
Borders are identified by their row and column indices.
Non-border cells are filled with spaces.
Efficiency:
Uses simple nested loops and conditional checks, making it efficient for small-to-moderate square sizes.