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.

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.