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

You can approximate a hollow circle in the console by printing stars only at grid points within a narrow ring. Nested for loops visit the grid, and an if statement checks whether each point lies between an inner and an outer radius.

Source code

Save this example as HollowCirclePatternExample.java. It uses a Java 25 compact source file with void main() and the IO console methods. Use JDK 25 or later; no preview flags or external libraries are required.

void main() {
    int radius = 5;
    int innerRadius = radius - 1;
    int outerRadiusSquared = radius * radius;
    int innerRadiusSquared = innerRadius * innerRadius;

    for (int y = -radius; y <= radius; y++) {
        for (int x = -radius; x <= radius; x++) {
            int distanceSquared = x * x + y * y;

            if (distanceSquared >= innerRadiusSquared
                    && distanceSquared <= outerRadiusSquared) {
                IO.print("* ");
            } else {
                IO.print("  ");
            }
        }
        IO.println();
    }
}

Explanation

Imagine a circle centered at (0, 0). The squared distance from the center to a point (x, y) is x * x + y * y. Comparing squared distances lets the program test positions without calculating square roots.

The outer radius is five, and the inner radius is four. A position contains a star when its squared distance is at least 16 and at most 25. This selects a ring between the two radii, including both boundaries.

Condition Purpose
distanceSquared >= innerRadiusSquared Exclude points strictly inside the inner circle.
distanceSquared <= outerRadiusSquared Exclude points outside the outer circle.

The logical AND operator, &&, requires both conditions to be true. Points too close to the center remain empty, as do points outside the ring.

The outer loop visits vertical coordinates from -radius through radius. The inner loop visits horizontal coordinates over the same range. Including both endpoints produces an 11-by-11 grid of logical positions for a radius of five.

Each star position prints "* ", and each empty position prints " ". Both strings occupy two character positions, preserving alignment. The extra horizontal spacing often makes the circle look more balanced because terminal characters are usually taller than they are wide. Its apparent proportions still depend on the font.

IO.print() stays on the current line, while IO.println() ends each grid row. The IO class belongs to java.lang, so no explicit import is needed.

The ring is an approximation on a discrete grid. Its edge will look stepped, and the number of stars per row will vary. Keep the radius small for this beginner example; very large values can overflow the int arithmetic and produce impractically large output.

Run the example

With JDK 25 or later installed, open a terminal in the directory containing the source file and run it directly:

java HollowCirclePatternExample.java

You can also compile the source file explicitly and then run the compiled program:

javac HollowCirclePatternExample.java
java HollowCirclePatternExample

Output

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

Display the output in a monospaced font to preserve alignment. Trailing spaces are omitted from the output shown here; leading spaces are preserved.

Try it yourself

Change radius to 8 and keep innerRadius = radius - 1. Compare the larger pattern with the original. More grid positions give the circle more detail, though its outline remains stepped.

For the original radius of five, change innerRadius to radius - 2. The inner radius becomes three, creating a thicker ring. Use an inner radius greater than zero and smaller than the outer radius to keep a hole in the center.

Try radius = 1 with the original innerRadius = radius - 1. The inner radius becomes zero, so the center is included and the result has no hole. Use a radius of at least two for a hollow pattern with this formula.

Finally, remove the inner-radius test and keep only distanceSquared <= outerRadiusSquared. The result becomes a filled circle, as in How do I print a circle pattern using loops in Java?.

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

You can print a butterfly pattern by placing two groups of stars on each row with a gap between them. Grow the groups toward the middle of the pattern, then shrink them again to create mirrored wings.

Source code

Save this example as ButterflyPatternExample.java. It uses a Java 25 compact source file with void main() and the IO console methods. Use JDK 25 or later; no preview flags or external libraries are required.

void main() {
    int halfHeight = 5;

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

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

Explanation

The variable halfHeight controls the number of rows from the top edge through the center, including the center row. For a positive value n, the complete pattern has 2 * n - 1 rows and a width of 2 * n characters.

The first outer loop counts from 1 through halfHeight. Each row contains three parts, printed by three inner loops in sequence:

  1. row stars for the left wing.
  2. 2 * (halfHeight - row) spaces for the middle gap.
  3. row stars for the right wing.

With halfHeight = 5, the upper half uses these counts:

Row counter Left stars Middle spaces Right stars
1 1 8 1
2 2 6 2
3 3 4 3
4 4 2 4
5 5 0 5

Each step adds one star to each wing and removes two spaces from the gap. The total width stays constant because row + 2 * (halfHeight - row) + row simplifies to 2 * halfHeight.

On the center row, the gap contains zero spaces. The middle loop does not execute, so the two groups meet and produce a solid line of ten stars.

The second outer loop starts at halfHeight - 1 and counts down to 1. It uses the same three inner loops, shrinking the wings and widening the gap. Starting one step below halfHeight prints the center row only once and mirrors the rows above it.

Each star and space occupies one character position. IO.print() writes the three parts on the current line, while IO.println() starts the next row. The IO class belongs to java.lang, so no explicit import is needed.

Run the example

With JDK 25 or later installed, open a terminal in the directory containing the source file and run it directly:

java ButterflyPatternExample.java

You can also compile the source file explicitly and then run the compiled program:

javac ButterflyPatternExample.java
java ButterflyPatternExample

Output

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

Display the output in a monospaced font to preserve alignment. The spaces between the wings are part of the pattern.

Try it yourself

Change halfHeight to 3, then to 7. Before running each version, calculate the total number of rows, the width, and the gap on the first row. For a positive value n, these are 2 * n - 1, 2 * n, and 2 * (n - 1), respectively.

Try halfHeight = 1. The first outer loop prints two adjacent stars, and the second outer loop does not execute. With a value of zero, neither outer loop executes and the program prints nothing. Use positive values to produce a visible pattern.

Change the second outer loop to start at row = halfHeight. This repeats the solid center row and produces a pattern with 2 * halfHeight rows instead.

Finally, compare the changing middle gap with the changing leading spaces in How do I print an hourglass pattern using loops in Java?. In both examples, the spaces are calculated from the current row counter.

How do I print an hourglass pattern using loops in Java?

You can print an hourglass pattern by combining a shrinking, centered triangle with a growing one. Nested for loops control the leading spaces and stars on each row. Print the narrowest row only once so the two halves meet at a single center star.

Source code

Save this example as HourglassPatternExample.java. It uses a Java 25 compact source file with void main() and the IO console methods. Use JDK 25 or later; no preview flags or external libraries are required.

void main() {
    int halfHeight = 5;

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

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

Explanation

The variable halfHeight sets the number of rows from the top edge through the center, including the center row. For a positive value n, the complete hourglass has 2 * n - 1 rows. A value of five therefore produces nine rows.

The first outer loop counts down from halfHeight to 1. For each value of row, it prints halfHeight - row leading spaces followed by 2 * row - 1 stars. The number of stars decreases by two per row, while the number of leading spaces increases by one.

With halfHeight = 5, the upper half looks like this:

Row counter Leading spaces Stars
5 0 9
4 1 7
3 2 5
2 3 3
1 4 1

The second outer loop reverses that progression. It starts at row = 2 and counts up to halfHeight, producing 3, 5, 7, and 9 stars. Starting at 2 avoids printing the single-star center row twice.

Both halves use the same spacing formulas. As the lower half grows, its leading-space count decreases, keeping the stars centered around the same column.

Each leading space and each star occupies one character position. IO.print() keeps writing on the current line, and IO.println() ends the row after both inner loops finish. The IO class belongs to java.lang, so no explicit import is needed.

Run the example

With JDK 25 or later installed, open a terminal in the directory containing the source file and run it directly:

java HourglassPatternExample.java

You can also compile the source file explicitly and then run the compiled program:

javac HourglassPatternExample.java
java HourglassPatternExample

Output

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

Display the output in a monospaced font to preserve alignment. Leading spaces are part of the pattern.

Try it yourself

Change halfHeight to 3, then to 7. Before running each version, calculate the total height and the number of stars in the widest row. Both are 2 * halfHeight - 1 for a positive value.

Try halfHeight = 1. The first outer loop prints one star, and the second outer loop does not execute. A zero or negative value produces no output because neither outer loop executes.

Change the second outer loop to start at row = 1. Observe how repeating the center row changes the shape and adds one line to the output.

Finally, compare this pattern with How do I print a diamond pattern using loops in Java?. A diamond grows toward its center and then shrinks; the hourglass shrinks toward its center and then grows.

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

You can print a hollow pyramid by placing stars along its two sloping sides and its base. Nested for loops control the leading spaces and the width of each row, while an if statement leaves the interior empty.

Source code

Save this example as HollowPyramidPatternExample.java. It uses a compact source file with void main() and the IO console methods. Use JDK 25 or later; no preview flags or external libraries are required. Compact source files allow the method to appear without an explicit class declaration. See the Java documentation on compact source files.

void main() {
    int height = 5;

    for (int row = 1; row <= height; row++) {
        for (int space = 0; space < height - row; space++) {
            IO.print(" ");
        }
        for (int column = 1; column <= 2 * row - 1; column++) {
            if (column == 1 || column == 2 * row - 1 || row == height) {
                IO.print("*");
            } else {
                IO.print(" ");
            }
        }
        IO.println();
    }
}

Explanation

The outer loop counts from 1 through height, producing one line for each row. Two inner loops run in sequence on that line.

The first inner loop prints height - row leading spaces. With a height of five, the leading-space counts are 4, 3, 2, 1, and 0. Reducing this count moves the left edge one position to the left on each successive row.

The second inner loop visits 2 * row - 1 positions. Its width increases through the odd numbers 1, 3, 5, 7, and 9. This makes the right edge move one position to the right while the left edge moves left, keeping the pyramid centered.

At each position, the condition checks whether a star belongs there:

Condition Purpose
column == 1 Print the left edge.
column == 2 * row - 1 Print the right edge.
row == height Fill the entire bottom row.

The logical OR operator, ||, selects a star when any of these conditions is true. All remaining positions contain a single space, creating the empty interior. On the first row, the left and right edges share one position, so only one star is printed.

Both the star and the empty position occupy one character. Use "*" rather than "* " here so the spacing matches the leading-space calculation.

IO.print() writes without ending the current line. After both inner loops finish, IO.println() starts the next row. The IO class is available without an explicit import because it belongs to java.lang.

Run the example

With JDK 25 or later installed, open a terminal in the directory containing the source file and run it directly:

java HollowPyramidPatternExample.java

The Java launcher compiles and runs the source file. You can also compile it explicitly and then run the compiled program:

javac HollowPyramidPatternExample.java
java HollowPyramidPatternExample

Output

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

Display the output in a monospaced font to preserve alignment. Leading spaces are part of the pattern.

Try it yourself

Change height to 3, then to 7. For each row, calculate the number of leading spaces and the row width before running the program. A positive height n produces n rows and a base of 2 * n - 1 stars.

Try height = 1, which prints a single star, and height = 2, which prints a tip above a three-star base. Neither has an empty interior. A zero or negative height produces no output because the outer loop never executes.

Finally, remove || row == height from the condition to leave the base open. Compare the result with the filled shape in How do I print a pyramid pattern using loops in Java?.

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

You can print a checkerboard pattern by alternating stars and empty positions across a grid. Use nested for loops to visit each position and the remainder operator % to decide which positions contain stars.

Source code

Save this example as CheckerboardPatternExample.java.

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

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

Explanation

The variable size sets both the number of rows and the number of logical columns. The outer loop selects each row, and the inner loop visits each column in that row. Both counters start at zero, so a size of eight gives indexes from 0 through 7.

The expression (row + column) % 2 calculates the remainder after dividing the sum of the indexes by two. A remainder of zero means the sum is even; a remainder of one means it is odd. The program prints a star for an even sum and an empty position for an odd sum.

For the first two rows, the condition works like this:

Row Column Sum Remainder Result
0 0 0 0 Star
0 1 1 1 Empty
0 2 2 0 Star
1 0 1 1 Empty
1 1 2 0 Star
1 2 3 1 Empty

Moving one position horizontally increases column by one, changing the sum from even to odd or from odd to even. Moving one position vertically increases row by one and also changes the parity. This makes neighboring positions alternate in both directions.

Using only column % 2 would repeat the same arrangement on every row and produce vertical stripes. Including row shifts the arrangement on alternate rows, creating the checkerboard pattern.

Each star position prints "* ", and each empty position prints " ". Both strings occupy two character positions, so the columns stay aligned. System.out.println() runs after the inner loop to start the next row.

Run the example

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

javac CheckerboardPatternExample.java
java CheckerboardPatternExample

Output

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

Display the output in a monospaced font to preserve alignment. Trailing spaces are omitted from the output shown here; leading spaces are preserved. Every row still contains eight logical positions, including empty positions at its edges. The stars mark alternating cells rather than drawing solid squares.

Try it yourself

Change size to 5. Odd sizes also work: the first and last positions of the first row both contain stars. With a size of five, the program prints 13 stars across 25 logical positions. With the original size of eight, it prints 32 stars across 64 logical positions.

Change the condition to (row + column) % 2 != 0 to swap the starred and empty positions. The top-left position will then be empty.

To make the empty cells visible while learning, replace System.out.print(" ") with System.out.print(". "). Both branches still print two characters, preserving alignment.

Finally, try size = 1, which prints a single star. A zero or negative size produces no output because the outer loop never executes.