Home » Java » Core Java » Java 13: Enhancements to Switch Expressions

About Fahd Shariff

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.

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.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

avatar

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

  Subscribe  
Notify of