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 square pattern using loops in Java?

You can print a square pattern with two nested for loops. The outer loop controls the rows, and the inner loop prints the same number of stars in each row.

Source code

Save this example as SquarePatternExample.java.

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

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

Explanation

The variable size determines both the number of rows and the number of stars per row. With size = 5, the outer loop runs five times. For each row, the inner loop also runs five times, producing 25 stars in total.

System.out.print("* ") prints a star followed by a space without starting a new line. After the inner loop finishes, System.out.println() moves to the next row. Placing that line break inside the inner loop would print each star on a separate line.

The pattern has equal numbers of rows and columns. Its apparent proportions depend on the terminal font and spacing; text cells are not necessarily square.

Run the example

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

javac SquarePatternExample.java
java SquarePatternExample

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 size to 3, then to 7. Before running the program, predict how many stars it will print using size * size.

How do I loop through an array in Java?

You can use an enhanced for loop, also called a for-each loop, to read each element in an array.

In this example, you will loop through an array of programming language names and print each name.

Source code

public class ArrayLoopExample {
    void main() {
        String[] languages = {"Java", "Python", "JavaScript"};

        for (String language : languages) {
            IO.println(language);
        }

        IO.println("Total languages: " + languages.length);
    }
}

Explanation

The following statement creates an array containing three strings:

String[] languages = {"Java", "Python", "JavaScript"};

String[] means that the variable holds an array of strings. Each value inside the braces is an element of the array.

The enhanced for loop reads the elements in their array order:

for (String language : languages) {
    IO.println(language);
}

On each iteration, language holds the next element:

Iteration Value of language
1 "Java"
2 "Python"
3 "JavaScript"

The loop ends after processing the last element. You do not need to manage an index or write a condition to stop the loop.

Finally, the program prints the number of elements using the array’s length field:

IO.println("Total languages: " + languages.length);

Use length without parentheses when working with arrays.

Run the example

Compile and run the file:

javac ArrayLoopExample.java
java ArrayLoopExample

Output

Java
Python
JavaScript
Total languages: 3

Use an enhanced for loop when you need to read each element. If you need the position of an element or want to replace values in the array, use an index-based for loop.

How do I choose a value using a switch expression in Java?

A switch expression selects and returns a value based on an input. You can assign the result directly to a variable.

In this example, you will convert a day number into a day name.

Source code

public class SwitchExpressionExample {
    void main() {
        int dayNumber = 3;

        String dayName = switch (dayNumber) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            case 4 -> "Thursday";
            case 5 -> "Friday";
            case 6 -> "Saturday";
            case 7 -> "Sunday";
            default -> "Unknown day";
        };

        IO.println("Day number: " + dayNumber);
        IO.println("Day name: " + dayName);
    }
}

Explanation

The variable dayNumber holds the value to check:

int dayNumber = 3;

The switch expression compares this value with each case. When it finds a match, it returns the value after the arrow (->).

For example:

case 3 -> "Wednesday";

Since dayNumber is 3, the expression returns "Wednesday". The result is assigned to dayName.

Arrow rules do not fall through to the next case, so you do not need a break statement.

The default rule handles values that do not match any listed case:

default -> "Unknown day";

A switch expression must cover every possible input. In this example, default handles integers outside the range of 1 through 7.

Notice the semicolon after the closing brace:

};

It ends the variable declaration that assigns the result of the switch expression to dayName.

The program uses void main() and IO.println(), both supported in Java 25 without preview options.

Run the example

Compile and run the file:

javac SwitchExpressionExample.java
java SwitchExpressionExample

Output

Day number: 3
Day name: Wednesday

If you change dayNumber to 9, the output becomes:

Day number: 9
Day name: Unknown day

How do I check if a number is even or odd in Java?

You can check whether an integer is even or odd using the remainder operator (%).

An even number has a remainder of zero when divided by two. An odd number has a nonzero remainder.

Source code

public class EvenOddExample {
    public static void main(String[] args) {
        int number = 27;

        if (number % 2 == 0) {
            IO.println(number + " is even.");
        } else {
            IO.println(number + " is odd.");
        }
    }
}

Explanation

The variable number stores the integer to check:

int number = 27;

The % operator returns the remainder after division. The following expression checks whether dividing number by two leaves a remainder of zero:

number % 2 == 0

If the condition is true, the program prints that the number is even. Otherwise, it prints that the number is odd.

For 27, the remainder is 1, so the program runs the else block.

This check also works with negative integers and zero:

Number Remainder when divided by 2 Result
28 0 Even
27 1 Odd
-28 0 Even
-27 -1 Odd
0 0 Even

To check directly for an odd number, use number % 2 != 0. Checking for a remainder of 1 would miss negative odd numbers.

The program displays the result using IO.println(), which is available in Java 25. No import is required for java.lang.IO.

Run the example

Compile and run the file:

javac EvenOddExample.java
java EvenOddExample

Output

27 is odd.

Change number to 28 and run the program again:

28 is even.