Java Program to Print a Hollow Square Pattern

1. Introduction

In this guide, we will develop a Java program that prints a hollow square pattern based on user input. A hollow square pattern consists of asterisks (*) on the border of the square, while the inside of the square remains empty. This type of pattern is a great exercise for practicing loops and conditional statements in Java, and it provides a visual understanding of how nested loops can be used to generate patterns.

2. Program Steps

1. Import the Scanner class to read the size of the square from the user.

2. Prompt the user to enter the size of the sides of the square.

3. Use nested loops to print the hollow square pattern: the outer loop for rows and the inner loop for columns.

4. Within the nested loops, use conditional statements to print asterisks (*) on the borders and spaces inside the square.

5. Compile and run the program, input the side size, and observe the hollow square pattern.

3. Code Program

import java.util.Scanner; // Import Scanner class

public class HollowSquarePattern {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // Create Scanner object
        System.out.print("Enter the size of the square: "); // Prompt for user input
        int size = scanner.nextInt(); // Read the size of the square from user

        for(int i = 1; i <= size; i++) { // Loop for each row
            for(int j = 1; j <= size; j++) { // Loop for each column
                if(i == 1 || i == size || j == 1 || j == size) { // Check for border
                    System.out.print("*"); // Print asterisk for border
                } else {
                    System.out.print(" "); // Print space for inside
                }
            }
            System.out.println(); // New line after each row
        }
        scanner.close(); // Close the scanner
    }
}

Output:

Enter the size of the square: 5
*****
*   *
*   *
*   *
*****

Explanation:

1. The program begins by importing the Scanner class, which is used to capture the size of the square sides as input from the user. This size determines both the width and the height of the square.

2. After reading the user's input for the size, the program uses a for loop to iterate over each row of the square.

3. Inside the row loop, another for loop iterates over each column. Conditional statements within the column loop check if the current row or column is on the border of the square (i == 1 || i == size || j == 1 || j == size). If so, an asterisk (*) is printed to form the border of the square. Otherwise, a space is printed, creating the hollow effect inside the square.

4. After completing the column loop for a row, the program prints a newline character to move to the next row, continuing this process until the entire square is printed.

5. Finally, the Scanner object is closed to avoid resource leaks, following best practices for input handling in Java.

Comments