Java Switch Expressions

Switch expressions, introduced in Java 14, provide a more concise and flexible way to use switch statements. They allow the switch statement to return a value and use the yield statement to produce that value.

Key Topics

1. Syntax

int result = switch (expression) {
    case value1 -> value1Result;
    case value2 -> value2Result;
    // You can have any number of case statements.
    default -> defaultValue;
};

2. Example

Example of using a switch expression:

public class SwitchExpressionExample {
    public static void main(String[] args) {
        int day = 3;
        String dayName = switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            case 4 -> "Thursday";
            case 5 -> "Friday";
            case 6 -> "Saturday";
            case 7 -> "Sunday";
            default -> "Invalid day";
        };
        System.out.println("Today is " + dayName);
    }
}

Output:

Today is Wednesday

3. Break Statement

In switch expressions, the break statement is replaced by the yield statement, which allows a value to be returned.

public class YieldExample {
    public static void main(String[] args) {
        int number = 2;
        String result = switch (number) {
            case 1 -> "Number is 1";
            case 2 -> "Number is 2";
            case 3 -> "Number is 3";
            default -> "Number is not 1, 2, or 3";
        };
        System.out.println(result);
    }
}

Output:

Number is 2

4. Default Case

The default case in switch expressions works similarly to traditional switch statements, handling any values not matched by the cases.

public class DefaultCaseExample {
    public static void main(String[] args) {
        int number = 4;
        String result = switch (number) {
            case 1 -> "Number is 1";
            case 2 -> "Number is 2";
            case 3 -> "Number is 3";
            default -> "Number is not 1, 2, or 3";
        };
        System.out.println(result);
    }
}

Output:

Number is not 1, 2, or 3

Key Takeaways

  • Switch expressions provide a concise way to return values based on a variable's value.
  • Use yield to return values within switch expressions.
  • The default case handles any values not matched by the cases.