Java Switch statement expressions jdk12+

ww‮al.w‬utturi.com
Java Switch statement expressions jdk12+

In Java 12 and later versions, you can use the switch expression feature to simplify the syntax of switch statements and return a value from the switch statement directly.

Here's an example of how to use a switch expression in Java:

int result = switch (x) {
    case 1 -> {
        // Code to be executed when x is 1
        yield 10;
    }
    case 2 -> {
        // Code to be executed when x is 2
        yield 20;
    }
    case 3 -> {
        // Code to be executed when x is 3
        yield 30;
    }
    default -> {
        // Code to be executed when x is not 1, 2, or 3
        yield 0;
    }
};

In this example, the switch expression has a yield statement in each case that returns a value from the switch expression. The value returned by the switch expression is stored in the result variable.

The syntax of a switch expression is similar to that of a switch statement, but it uses the -> operator instead of the : operator to separate the case labels from the case bodies. The case bodies can contain any valid Java statements, including local variable declarations and control statements such as break and return.

You can find more information about the switch expression feature and how to use it in Java in the Java documentation.

Created Time:2017-10-17 20:18:52  Author:lautturi