Discover the Switch expressions of Java 12

Java 12, which has been 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.

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:

Leave a Reply

Your email address will not be published. Required fields are marked *