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. |
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
Thank you!
We will contact you soon.
👁 Photo of Fahd Shariff
Fahd ShariffNovember 14th, 2019Last Updated: November 5th, 2019
Fahd ShariffNovember 14th, 2019Last Updated: November 5th, 2019
0 299 1 minute read

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