Solid And Hollow Rectangle Star Pattern In Java Program
Creating star patterns in Java is a fundamental exercise for understanding loops and conditional statements. These patterns are not just visual puzzles; they serve as an excellent way to grasp how nested loops can control output in a grid-like fashion. In this article, you will learn how to programmatically generate both solid and hollow rectangle star patterns using Java.
Problem Statement
The challenge is to design a Java program that can print two distinct rectangular patterns composed of asterisks (*):
- Solid Rectangle: A filled rectangle of a specified width and height.
- Hollow Rectangle: A rectangle where only the border is made of stars, and the interior is filled with spaces.
This problem emphasizes the control flow capabilities of Java, specifically using nested for loops and conditional logic to precisely place characters on the console.
Example
Consider a rectangle with 5 rows and 7 columns.
Solid Rectangle Output:
*******
*******
*******
*******
*******
Hollow Rectangle Output:
*******
* *
* *
* *
*******
Background & Knowledge Prerequisites
To effectively understand and implement these Java programs, readers should have a basic grasp of the following Java concepts:
- Variables: Declaring and initializing integer variables.
- Input/Output: Using
java.util.Scannerto read user input, andSystem.out.print()along withSystem.out.println()for console output. - Loops: Understanding the
forloop, particularly nestedforloops, to iterate through rows and columns. - Conditional Statements: Using
ifandelsestatements to apply different logic based on conditions.
No special imports or advanced setups are required beyond the standard Java Development Kit (JDK).
Use Cases or Case Studies
While direct "real-world" applications for star patterns are limited to ASCII art or console-based games, the underlying concepts are widely applicable:
- Learning Fundamentals: Excellent for beginners to visualize and understand nested loops and conditional logic.
- Debugging Logic: Helps in developing systematic thinking for iterating over 2D structures (like matrices or grids).
- Basic Graphics: The principles extend to rendering simple shapes in character-based interfaces or even pixel-based graphics by controlling individual "pixels" (characters).
- Text-based UI/UX: In older or very minimal console applications, such patterns could be used for simple borders or separators.
- Algorithm Practice: A common interview question or practice problem to assess a candidate's grasp of basic programming constructs.
Solution Approaches
We will explore two distinct approaches for creating these patterns, each building upon the concept of nested loops.
Approach 1: Solid Rectangle Pattern
This approach uses nested for loops to iterate through each position in the rectangle and prints an asterisk at every single one.
- One-line summary: Use two nested loops to print an asterisk for every row and column, followed by a newline character after each row.
// Solid Rectangle Star Pattern
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Prompt user for the number of rows
System.out.print("Enter the number of rows for the solid rectangle: ");
int rows = scanner.nextInt();
// Step 2: Prompt user for the number of columns
System.out.print("Enter the number of columns for the solid rectangle: ");
int cols = scanner.nextInt();
System.out.println("\\nSolid Rectangle Pattern:");
// Step 3: Outer loop iterates through each row
for (int i = 0; i < rows; i++) {
// Step 4: Inner loop iterates through each column in the current row
for (int j = 0; j < cols; j++) {
// Step 5: Print an asterisk for every position
System.out.print("*");
}
// Step 6: After printing all columns for a row, move to the next line
System.out.println();
}
scanner.close();
}
}
Sample Output:
Enter the number of rows for the solid rectangle: 4
Enter the number of columns for the solid rectangle: 6
Solid Rectangle Pattern:
******
******
******
******
Stepwise Explanation:
- Input Collection: The program first prompts the user to enter the desired number of
rowsandcolsfor the rectangle using aScannerobject. - Outer Loop (Rows): An outer
forloop, controlled by variablei, runs from0up torows - 1. Each iteration of this loop represents a new row in the rectangle. - Inner Loop (Columns): An inner
forloop, controlled by variablej, runs from0up tocols - 1. This loop executes completely for each iteration of the outer loop. - Printing Asterisks: Inside the inner loop,
System.out.print("*")is used.print()(instead ofprintln()) ensures that each asterisk is printed on the same line, side-by-side, forming a row. - Newline Character: After the inner loop finishes (meaning all asterisks for the current row have been printed),
System.out.println()is called. This moves the cursor to the beginning of the next line, ensuring that the next row of asterisks starts on a new line.
Approach 2: Hollow Rectangle Pattern
This approach builds upon the solid rectangle by adding conditional logic inside the inner loop. An asterisk is printed only if the current position is on the border of the rectangle; otherwise, a space is printed.
- One-line summary: Use nested loops and an
if-elsecondition to print stars only for positions in the first/last row or first/last column, and spaces otherwise.
// Hollow Rectangle Star Pattern
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Prompt user for the number of rows
System.out.print("Enter the number of rows for the hollow rectangle: ");
int rows = scanner.nextInt();
// Step 2: Prompt user for the number of columns
System.out.print("Enter the number of columns for the hollow rectangle: ");
int cols = scanner.nextInt();
System.out.println("\\nHollow Rectangle Pattern:");
// Step 3: Outer loop iterates through each row
for (int i = 0; i < rows; i++) {
// Step 4: Inner loop iterates through each column in the current row
for (int j = 0; j < cols; j++) {
// Step 5: Check if the current position is on the border
// Border conditions: first row (i==0), last row (i==rows-1),
// first column (j==0), last column (j==cols-1)
if (i == 0 || i == rows - 1 || j == 0 || j == cols - 1) {
System.out.print("*"); // Print star if on border
} else {
System.out.print(" "); // Print space if in the interior
}
}
// Step 6: After printing all columns for a row, move to the next line
System.out.println();
}
scanner.close();
}
}
Sample Output:
Enter the number of rows for the hollow rectangle: 5
Enter the number of columns for the hollow rectangle: 8
Hollow Rectangle Pattern:
********
* *
* *
* *
********
Stepwise Explanation:
- Input Collection: Similar to the solid rectangle, the program takes
rowsandcolsas input. - Nested Loops: The structure of the nested
forloops remains the same, iterating through every(i, j)coordinate within therows x colsgrid. - Conditional Logic (Key Difference): Inside the inner loop, an
if-elsestatement is introduced:
-
if (i == 0 || i == rows - 1 || j == 0 || j == cols - 1): This is the core condition. It checks if the current position (i,j) is either in the first row (i == 0), the last row (i == rows - 1), the first column (j == 0), or the last column (j == cols - 1). If any of these conditions are true, the position is part of the border. - Print Star: If the condition is true,
System.out.print("*")prints an asterisk. - Print Space: If the condition is false (meaning the position is *not* on any border),
System.out.print(" ")prints a space, creating the hollow effect.
- Newline: After each row is complete,
System.out.println()ensures the next row starts on a new line.
Conclusion
Mastering star patterns in Java is a rewarding way to build foundational programming skills. The solid rectangle pattern teaches the basic use of nested loops for repetitive output, while the hollow rectangle pattern introduces the crucial concept of conditional logic within loops to create more intricate designs. These patterns demonstrate how simple constructs can be combined to produce structured and visually appealing outputs.
Summary
- Solid Rectangle: Created using nested
forloops, printing an asterisk for every(row, column)position. - Hollow Rectangle: Created using nested
forloops with anif-elsecondition. An asterisk is printed only if the current position is on thefirst row (i=0),last row (i=rows-1),first column (j=0), orlast column (j=cols-1). Otherwise, a space is printed. - Key Learning: These patterns reinforce understanding of
forloops,System.out.print/println, and conditional (if-else) statements in Java. - Practicality: Excellent for beginners to visualize control flow and practice basic algorithm design.