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.

How do I convert a double to an int in Java?

You can convert a double value to an int using an explicit cast. This removes the fractional part of the number.

This example converts both positive and negative values so you can see how the conversion works.

Source code

public class DoubleToIntExample {
    public static void main(String[] args) {
        double positiveValue = 42.75;
        double negativeValue = -42.75;

        int positiveResult = (int) positiveValue;
        int negativeResult = (int) negativeValue;

        System.out.println("Original positive value: " + positiveValue);
        System.out.println("Converted positive value: " + positiveResult);

        System.out.println("Original negative value: " + negativeValue);
        System.out.println("Converted negative value: " + negativeResult);
    }
}

Explanation

A double can store a fractional value, while an int stores a whole number within its supported range.

To convert a double to an int, place (int) before the value:

int positiveResult = (int) positiveValue;

The cast converts 42.75 to 42. It removes the fractional part instead of rounding to the nearest integer.

For negative numbers, the conversion also removes the fractional part:

int negativeResult = (int) negativeValue;

This converts -42.75 to -42, not -43. For finite values within the int range, the conversion truncates toward zero.

Java requires an explicit cast for this assignment because converting a double to an int can lose information. Without the cast, the following statement would cause a compilation error:

int positiveResult = positiveValue;

Run the example

With JDK 25 or later installed, compile and run the file:

javac DoubleToIntExample.java
java DoubleToIntExample

Output

Original positive value: 42.75
Converted positive value: 42
Original negative value: -42.75
Converted negative value: -42

Special values and limits

An int can store values from -2147483648 to 2147483647. Casting a double does not throw an exception when the value exceeds this range.

Input Result after casting to int
A value above the maximum int value Integer.MAX_VALUE
A value below the minimum int value Integer.MIN_VALUE
Double.POSITIVE_INFINITY Integer.MAX_VALUE
Double.NEGATIVE_INFINITY Integer.MIN_VALUE
Double.NaN 0

Use an explicit cast when you want to discard the fractional part. If you need rounding to the nearest integer, use a rounding method such as Math.round() instead; its double overload returns a long.