2 min read

Java is preparing to support pattern matching, part of which is revamping the switch statement. The changes are going to allow the switch statement to be used as both statements and as an expression. The changes to the switch statement will simplify everyday coding. It will also pave the way for the use of pattern matching in switch.

The current Java switch statement is similar to the ones in languages such as C and C++. It supports fall-through semantics by default. This traditional control flow is often useful for writing low-level code but is error-prone in switch statements used in higher-level code.

Brian Goetz, architect at Oracle has proposed to add a new simplified form, with new “case L ->” switch labels in addition to traditional switch blocks. On label match, only the statement or expression to the right of an arrow label is executed. For example, consider the following method:

static void howMany(int k) {
   switch (k) {
       case 1 -> System.out.println("one");
       case 2 -> System.out.println("two");
       case 3 -> System.out.println("many");
   }
}

On calling the function on these values:

howMany(1);
howMany(2);
howMany(3);

This is the output:

one
two
many

A new form of switch label, written “case L ->” is proposed to be added. This is an effort to imply that only the code to the right of the label is to be executed if the label is matched.

Like a switch statement, a switch expression can also use a traditional switch block with “case L:” switch labels. Most switch expressions have only one expression to the right of the “case L ->” switch label. When a full block is needed, the break statement is extended to take an argument.

The cases of a switch expression must contain a matching switch label for any possible value. In practice, this means that a default clause is required.

An enum switch expression covers all known cases. In this case, a default clause can be inserted by the compiler indicating that the enum definition has changed between compile-time and runtime. This is done manually by developers today, but having the compiler insert is less intrusive. Also, a switch expression must execute normally with a value or throw an exception.

This has a number of consequences like the compiler checking every switch label. Another consequence is that the control statements like break, return and continue, not being able to jump through a switch expression.

For more information visit the official OpenJDK post.

Read next

No more free Java SE 8 updates for commercial use after January 2019

Dagger 2.17, a dependency injection framework for Java and Android, is now out!

Build Java EE containers using Docker [Tutorial]

Data science enthusiast. Cycling, music, food, movies. Likes FPS and strategy games.

LEAVE A REPLY

Please enter your comment!
Please enter your name here