Switch statement in Java – Part 2

In the previous tutorial, I introduced you to the basic knowledge of the switch statement in Java. In this tutorial, I will talk more about the new features that Java supports from version 14 onwards!

Switch from Java 14

When working with a switch statement, you can encounter the following problems:

  • The first problem is that we forget to declare the break statement: this means that our code will not exit the switch statement after matching the first case but will continue the next case, for example:

Result:

Java enhancements for Switch statement since Java 12

  • The second problem is if we want in case the value of the variable with different values a and b, we will handle the same code. We will write the following code:

Or:

These ways of writing are inconvenient because of duplicating the code, or we sometimes can’t control it, where should we put a break statement?

  • The third problem is that if you want to use a switch statement to determine the value of a variable, you must write the following:

To solve these problems, from Java 14, you can write a switch statement with the following improvements:

  • For the first problem, Java 14 now supports us in writing a switch statement like a lambda expression, for example. as:

Result:

Java enhancements for Switch statement since Java 12

  • For the second problem, you can rewrite the switch statement as follows:

Result:

Java enhancements for Switch statement since Java 12

  • As for the third problem, now Java 12 has supported us to return a value with a switch expression as follows:

Result:

Java enhancements for Switch statement since Java 12

If you want to add code to handle business logic in each case of the switch expression, then you can add the code to use the yield keyword to return the value you want. The example is as follows:

Result:

Java enhancements for Switch statement since Java 12

Switch from Java 16

Since Java 16, the switch supports pattern matching similar to the instanceof operator from Java 14.

For example, I have an interface with two implementations as follows:

To check and print the implementation of a Shape object, we would normally write code like this:

From Java 16, you can write briefly with the switch as follows:

In this case, you must declare the default case! Because the shape object may not be in the implementations that we declared in the cases.

Switch từ Java 23 Preview

Since Java 23 Preview, switch statement supports pattern matching with primitive types! That means, now you can write:

Result:

Add Comment