Core Java

Java 13: Enhancements to Switch Expressions

You may remember from my previous post that, in Java 12, the traditional switch statement was enhanced so that it could be used as an expression. In Java 13, there has been a further change to this feature. The break statement can no longer return a value. Instead, you have to use the new yield statement, as shown below:

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);
      yield output;
    }
    default -> throw new IllegalArgumentException("Invalid input " + input);
};

Note that this is still a preview language feature, which means that it must be explicitly enabled in the Java compiler and runtime using the --enable-preview flag.

Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 13: Enhancements to 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