Java 16 Second Preview of Switch Expressions (JEP 361)

Java 16 introduced the second preview of switch expressions, which is a new feature that allows you to use the switch statement as an expression in Java. Switch expressions are an improved version of the traditional switch statement that allows you to use the switch statement in more contexts and to make it more concise and expressive.

Here is an example of how to use switch expressions in Java:

int result = switch (input) {
  case "a" -> 1;
  case "b" -> 2;
  default -> 0;
};

In this example, we are using a switch expression to evaluate the value of the input variable and to assign the result to the result variable. The switch expression consists of a switch block that defines the cases and a arrow operator (->) that separates the case labels from the case bodies. The case bodies can be any expressions that produce a value, and the value of the switch expression is the value of the case body that is executed.

Switch expressions also support the yield keyword, which allows you to return a value from the switch block and exit the switch expression early.

int result = switch (input) {
  case "a" -> 1;
  case "b" -> 2;
  case "c" -> {
    int temp = compute();
    yield temp;
  }
  default -> 0;
};

In this example, we are using the yield keyword to return the value of the temp variable from the switch block and to exit the switch expression early.

Switch expressions are an improvement over traditional switch statements because they allow you to use the switch statement as an expression, which means that you can use it in contexts where you can use other expressions, such as in assignments, method calls, and lambda expressions. They also allow you to use the yield keyword to return values from the switch block and to make the switch statement more concise and expressive.

One important thing to note about switch expressions is that they are currently in preview, which means that they are experimental and may change in future releases. They are also subject to additional restrictions and requirements, such as the need to enable the preview feature explicitly and the need to comply with the terms of the Switch Expressions preview license.