Pattern matching for switch (final in Java 21) lets case labels match on types, not just constant values. Each case can test the type, bind a variable, and add a condition with when. It replaces long if-else instanceof chains with a clear, exhaustive switch.
Key Points: • case Integer i -> ... matches any Integer and binds it to i. • Guards refine a case: case String s when s.length() > 5 -> .... • case null can now be handled directly, instead of the switch throwing NullPointerException. • More specific cases must come before general ones. The compiler rejects a case that can never match (dominance). • With sealed types, the compiler knows every subtype, so no default branch is needed.
Code Example:
public class SwitchPatternDemo {
static String classify(Object obj) {
return switch (obj) {
case null -> "null value";
case Integer i when i < 0 -> "negative integer " + i;
case Integer i -> "integer " + i;
case String s when s.length() > 5 -> "long string " + s;
case String s -> "short string " + s;
case Double d -> String.format("double %.2f", d);
default -> "other type: " + obj.getClass().getSimpleName();
};
}
public static void main(String[] args) {
Object[] values = {-7, 42, "Java", "Interview", 3.14159, null, 'x'};
for (Object v : values) {
System.out.println(classify(v));
}
}
}Output:
negative integer -7 integer 42 short string Java long string Interview double 3.14 null value other type: Character
Good to Know: A common follow-up is "Why is the order of cases important?" Because case Integer i before case Integer i when i < 0 would make the guarded case unreachable, and the compiler reports an error. Specific cases always go first.
Interview Tip: A concise interview answer is:
"In Java 21, switch can match on types, bind a variable and add a condition with when, and it can handle null directly. It replaces long if-else instanceof chains, and with sealed types the compiler checks that every case is covered."
Previous question: What is pattern matching for instanceof in Java 16?
Next question: What are record patterns in Java 21?