Switch statement in Java – Part 2

Switch from Java 12

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 12, you can write a switch statement with the following improvements:

  • For the first problem, Java 12 now supports us on how to write a switch statement like 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 value with a switch expression as follows:

Result:

Java enhancements for Switch statement since Java 12

Switch from Java 13

If you want to add code to handle business logic in each case of the switch expression, then you can upgrade to Java 13 and 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 17

Since Java 17, 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 17, 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

Since Java 23, switch statements support pattern matching with primitive types! That means, now you can write:

Result:

Add Comment