How do I print a rectangle pattern using loops in Java?

To print a rectangle pattern, use separate variables for its height and width. Nested loops let you control the number of rows independently from the number of stars in each row.

Source code

Save this example as RectanglePatternExample.java.

public class RectanglePatternExample {
    public static void main(String[] args) {
        int height = 4;
        int width = 8;

        for (int row = 0; row < height; row++) {
            for (int column = 0; column < width; column++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Explanation

The outer loop uses height, so it produces four rows. The inner loop uses width, so each row contains eight stars. The program prints height * width, or 32, stars.

The inner loop starts again at column = 0 every time the outer loop begins a new row. This reset makes every row the same length.

System.out.print() keeps the stars on the current line, while System.out.println() ends the row. Use positive values for both dimensions to produce a visible rectangle. With these loop conditions, a zero or negative height produces no rows; a positive height and nonpositive width produces blank lines.

Run the example

With a JDK installed, open a terminal in the directory containing the source file and run:

javac RectanglePatternExample.java
java RectanglePatternExample

Output

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

Display the output in a monospaced font to keep the pattern aligned. Trailing spaces are omitted from the output shown here.

Try it yourself

Change height to 6 and width to 3. Observe how changing each loop limit changes a different dimension of the pattern.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.