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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.