Discover the Switch expressions of Java 12

Java 12, which will be released in March, focuses on developments related to the internal operations of the JDK. Few additional features will have a real impact on Java developers on a daily basis.

Image for post
Image for post

Nevertheless, there is one that will have a real impact. It concerns switch expressions that are extended with Java 12. This new feature is in preview. Indeed, functionalities affecting the Java language itself or the JVM may now be integrated in a major version in order to allow developers in the community to test it in real conditions and then make their feedback to Oracle. Implementations are fully specified and implemented but not necessarily permanent.

In this case, the extension of the switch, which becomes an expression, aims to simplify the daily life of developers while preparing the future introduction of pattern matching in Java which will be based on the switch expressions.

In concrete terms, the changes concerning the switch are of two kinds:

  • Introduction of the new syntax case L -> which removes the obligation to use a break instruction simply because only the instruction or instruction block after the arrow is executed.
  • The switch can now be an expression. It can therefore have a value or return a value.

All this gives us the following examples of how to use the extended switch:

Starting from this example of days of the week, we can use a switch as an expression with the syntax case L -> and an instruction block placed to the right of the arrow :

As the extended switch are in preview mode in Java 12, you will need to enable them at compile and runtime in order to test them in your programs.

To do this, it will be necessary to do the following:

We can only hope that Java 13 scheduled for September 2019 will include more features to improve the daily work of developers.

If you want to discover some books to learn Java programming, I advice you to read the following article with my selection of the Top 6 Best Books for Java programming :

Written by

Entrepreneur / Developer / Blogger / Author. In Bitcoin We Trust: https://www.inbitcoinwetrust.net

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store