Pattern Matching for Switch
2 min readMay 22, 2023
Pattern Matching for Switch is a feature introduced in Java 14 as a preview feature and became a standard feature starting from Java 17. It enhances the switch statement by allowing pattern matching to be used within the switch expressions, making the code more concise and expressive.
Here’s how Pattern Matching for Switch works:
- Traditional Switch Statement: In Java, the switch statement allows you to evaluate an expression and perform different actions based on its value. Here’s an example of a traditional switch statement:
String fruit = "apple";
switch (fruit) {
case "apple":
System.out.println("Selected fruit is an apple");
break;
case "banana":
System.out.println("Selected fruit is a banana");
break;
default:
System.out.println("Selected fruit is unknown");
break;
}
- Pattern Matching for Switch: With the introduction of Pattern Matching for Switch, you can use patterns directly in the switch expressions, eliminating the need for explicit checks and casting.
Here’s an example:
String fruit = "apple";
switch (fruit) {
case "apple" -> System.out.println("Selected fruit is an apple");
case "banana" -> System.out.println("Selected fruit is a banana");
default -> System.out.println("Selected fruit is unknown");
}
- In this example, the arrow (
->
) is used to separate the pattern from the code to be executed. The patterns are matched against the switch expression, and the corresponding code block is executed for the matching pattern. - Pattern Matching for Switch allows for more expressive and concise code, especially when dealing with complex data structures or object hierarchies. It can match not only constant values but also other patterns such as type patterns, null patterns, and more.
It’s important to note that Pattern Matching for Switch is a powerful feature, but it should be used judiciously and appropriately in situations where it enhances code readability and maintainability.