How do I print a hollow square pattern using loops in Java?

You can print a hollow square by combining nested for loops with an if statement. The loops visit every position in a square grid, while the condition prints stars only along its border. Positions inside the square contain spaces.

Source code

Save this example as HollowSquarePatternExample.java.

public class HollowSquarePatternExample {
    public static void main(String[] args) {
        int size = 5;

        for (int row = 0; row < size; row++) {
            for (int column = 0; column < size; column++) {
                if (row == 0 || row == size - 1
                        || column == 0 || column == size - 1) {
                    System.out.print("* ");
                } else {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }
}

Explanation

The variable size controls both the number of rows and the number of logical columns. The outer loop visits each row, and the inner loop visits each column in that row. Both counters start at 0 and stop before size, so the last index is size - 1.

A position belongs to the border when at least one of these conditions is true:

Condition Border
row == 0 Top
row == size - 1 Bottom
column == 0 Left
column == size - 1 Right

The || operator means logical OR. If any border condition is true, the program prints "* ". Otherwise, it prints " " to leave the interior empty.

Both strings occupy two character positions. Using only one space for an empty position would shift the right border to the left on the middle rows.

For size = 5, the first and last rows contain five stars each. The three middle rows contain a star at each end and three empty positions between them. The output contains 16 stars in total.

System.out.print() stays on the current line. After the inner loop finishes, System.out.println() starts the next row. Keep this line break inside the outer loop and outside the inner loop.

Run the example

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

javac HollowSquarePatternExample.java
java HollowSquarePatternExample

Output

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

Display the output in a monospaced font to keep the pattern aligned. Trailing spaces are omitted from the output shown here. The pattern has equal numbers of logical rows and columns; its apparent proportions depend on the font and character spacing.

Try it yourself

Change size to 3, then to 7. For a size of at least two, the number of border stars is 4 * (size - 1): the top and bottom rows contribute 2 * size stars, and the remaining rows contribute 2 * (size - 2) stars.

Also try size = 1 and size = 2. The first prints a single star; the second prints four stars. Neither has an empty interior. A zero or negative size produces no output because the outer loop never executes.

To review how nested loops print every position, see How do I print a square pattern using loops in Java?.

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

You can approximate a filled circle in the console by visiting points on a grid and printing a star when a point lies inside the circle. This example combines nested loops with an if statement.

Source code

Save this example as CirclePatternExample.java.

public class CirclePatternExample {
    public static void main(String[] args) {
        int radius = 5;

        for (int y = -radius; y <= radius; y++) {
            for (int x = -radius; x <= radius; x++) {
                if (x * x + y * y <= radius * radius) {
                    System.out.print("* ");
                } else {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }
}

Explanation

Imagine a circle centered at (0, 0). A grid point (x, y) is inside or on its boundary when x * x + y * y <= radius * radius. Comparing squared values avoids calculating a square root.

The outer loop visits the vertical coordinates from -radius to radius. The inner loop visits the horizontal coordinates over the same range. Both endpoints are included, so a radius of five produces an 11-by-11 grid of logical cells.

For each point, the if statement prints a star and a space when the point belongs to the circle. Otherwise, it prints two spaces. Both branches occupy two character positions, preserving column alignment. This spacing often makes the circle look more balanced because terminal characters are usually taller than they are wide.

The result is a coarse approximation of a filled circle, not a smooth outline. Its appearance depends on the radius and terminal font. Keep the radius small for this beginner example: very large values can overflow the int multiplications and produce an impractically large output.

Run the example

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

javac CirclePatternExample.java
java CirclePatternExample

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

Try radii of 3 and 8. Compare the edges and observe how a larger grid gives the circle more detail.

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

You can build a diamond pattern by combining a growing pyramid with a shrinking pyramid. Print the widest row only once so the two halves meet at a single center row.

Source code

Save this example as DiamondPatternExample.java.

public class DiamondPatternExample {
    public static void main(String[] args) {
        int halfHeight = 5;

        for (int row = 1; row <= halfHeight; row++) {
            for (int space = 0; space < halfHeight - row; space++) {
                System.out.print(" ");
            }
            for (int star = 0; star < 2 * row - 1; star++) {
                System.out.print("*");
            }
            System.out.println();
        }

        for (int row = halfHeight - 1; row >= 1; row--) {
            for (int space = 0; space < halfHeight - row; space++) {
                System.out.print(" ");
            }
            for (int star = 0; star < 2 * row - 1; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Explanation

The first outer loop prints the top half, including the widest row. Its row value increases from 1 to halfHeight. Each row prints halfHeight - row spaces followed by 2 * row - 1 stars.

The second outer loop prints the bottom half. It starts at halfHeight - 1 to avoid repeating the widest row, and decreases to 1. As row decreases, there are more leading spaces and fewer stars.

For a positive halfHeight, the diamond has 2 * halfHeight - 1 rows and the same number of stars in its widest row. A value of five therefore produces nine rows with nine stars across the center. Use a monospaced font to preserve alignment.

Run the example

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

javac DiamondPatternExample.java
java DiamondPatternExample

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 halfHeight to 3. Then try 1 and observe why the bottom loop does not execute for that value.

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

To print a centered pyramid, print leading spaces before the stars on each row. As the row number increases, the number of spaces decreases and the number of stars increases.

Source code

Save this example as PyramidPatternExample.java.

public class PyramidPatternExample {
    public static void main(String[] args) {
        int height = 5;

        for (int row = 1; row <= height; row++) {
            for (int space = 0; space < height - row; space++) {
                System.out.print(" ");
            }
            for (int star = 0; star < 2 * row - 1; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Explanation

Each row contains two parts: leading spaces and stars. The first inner loop prints height - row spaces. The second inner loop prints 2 * row - 1 stars, giving the sequence 1, 3, 5, 7, and 9.

For a height of five, the first row has four spaces and one star. The last row has no leading spaces and nine stars. Adding two stars per row keeps the pyramid centered in a monospaced font.

This example prints "*" instead of "* ". Each star and each space occupies one character position, which makes the centering formula work as written. The two inner loops run one after the other for every row.

Run the example

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

javac PyramidPatternExample.java
java PyramidPatternExample

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

Set height to 3. Calculate the number of leading spaces and stars for each row before running the program.

How do I print a right triangle pattern using loops in Java?

You can print a right triangle by increasing the number of stars on each row. Unlike a rectangle, the inner loop limit depends on the current row number.

Source code

Save this example as RightTrianglePatternExample.java.

public class RightTrianglePatternExample {
    public static void main(String[] args) {
        int height = 5;

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

Explanation

The outer loop counts from 1 through height, including the last row. The inner loop counts from 1 through row. As a result, row 1 contains one star, row 2 contains two stars, and row 5 contains five stars.

The condition column <= row creates the sloping edge. If you replace row with height in that condition, every row contains the same number of stars and the output becomes a square pattern.

For a positive height n, the total number of stars is 1 + 2 + ... + n, which equals n * (n + 1) / 2. This example prints 15 stars.

Run the example

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

javac RightTrianglePatternExample.java
java RightTrianglePatternExample

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

Print an inverted triangle by changing the outer loop to for (int row = height; row >= 1; row--). Keep the inner loop unchanged.