How does pattern matching for switch work in Java, and what does it change for you?
Pattern matching for switch lets a switch statement choose its branch by the type of the value and not just by its value, and it binds the value to a name as it does so.
Before this, you had to write a chain of instanceof tests and casts. Now the switch itself does the testing.
public class Main {
public static void main(String[] args) {
System.out.println(describe("hello"));
System.out.println(describe(42));
System.out.println(describe(3.5));
System.out.println(describe(null));
}
static String describe(Object value) {
return switch (value) {
case String text -> "a string of " + text.length() + " characters";
case Integer number -> "the number " + number;
case Double number -> "the decimal " + number;
case null -> "nothing at all";
default -> "something else";
};
}
}
So what does it change for you? Four things.
The first one is that you no longer need the chain of instanceof tests and casts. The branch matches by type and gives you the value already cast, so there is nothing to convert by hand.
The second one is that the null case can be handled properly. Before this, a switch on a null value threw a NullPointerException, and you had to check for null before the switch. Now you can write case null and it is matched like any other case.
The third one is that you can add a condition to a case with the word when. So case String text when text.length() > 3 matches only the longer strings.
The fourth one is that the compiler can check that you handled every case, which is the subject of the last question in this topic.
The next question in this topic looks at what happens when you leave a case out.