Java 21 - Pattern Matching for Switch - Part 2
Sanjoy Kumar Malik .
Senior Software Architect - Java Architect, Cloud Architect, AWS Architect?? All views are my own
In the Part 1, I discussed about improved enum constants as case labels in Java 21. In this article, I will focus on patterns in switch labels.
In general, the value of the selector expression is compared with the case label by an equality test. But this mechanism changes when patterns come at the case label. In this case, label is selected based on the result of pattern matching. Remember, a pattern case label can apply to multiple values. Have a look at the below code snippet:
In the above code, when the method call patternCaseLabelTest(cs) gets executed, the value of obj matches the pattern CharSequence cs, and the expression associated with the label case CharSequence cs is evaluated.
Now consider the below code:
In the above code, pay close attention to the below code snippet:
Here, we are further checking the result of pattern matching before executing the logic associated with that label. We can merge these two tests using guarded pattern case labels as follows:
case CharSequence cs when cs.toString().contains("Jupiter") -> cs.toString();
case CharSequence cs when !cs.toString().contains("Jupiter") -> throw new RuntimeException("Wrong message");
The final program will look like below:
The when clause is optional. This is a Boolean expression. The when clause is known as the guard.
That’s it for this article. I will discuss more on?Pattern Matching for Switch in Java 21?in my upcoming articles.