Core Java

Java 12: Switch Expressions

In Java 12, the switch statement has been enhanced so that it can be used as an expression. It is now also possible to switch on multiple constants in a single case, resulting in code that is more concise and readable. These enhancements are a preview language feature, which means that they must be explicitly enabled in the Java compiler and runtime using the --enable-preview flag.

Consider the following switch statement:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
int result = -1;
switch (input) {
  case 0:
  case 1:
    result = 1;
    break;
  case 2:
    result = 4;
    break;
  case 3:
    System.out.println("Calculating: " + input);
    result = compute(input);
    System.out.println("Result: " + result);
    break;
  default:
    throw new IllegalArgumentException("Invalid input " + input);
}

In Java 12, this can be rewritten using a switch expression as follows:

01
02
03
04
05
06
07
08
09
10
11
final int result = switch (input) {
  case 0, 1 -> 1;
  case 2 -> 4;
  case 3 -> {
    System.out.println("Calculating: " + input);
    final int output = compute(input);
    System.out.println("Result: " + output);
    break output;
  }
  default -> throw new IllegalArgumentException("Invalid input " + input);
};

As illustrated above:

  • The switch is being used in an expression to assign a value to the result integer
  • There are multiple labels separated with a comma in a single case
  • There is no fall-through with the new case X -> syntax. Only the expression or statement to the right of the arrow is executed
  • The break statement takes an argument which becomes the value returned by the switch expression (similar to a return)

Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 12: Switch Expressions

Opinions expressed by Java Code Geeks contributors are their own.

Fahd Shariff

Fahd is a software engineer working in the financial services industry. He is passionate about technology and specializes in Java application development in distributed environments.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button