Pattern matching in switch
Code Comparison
String format(Object obj) {
if (obj instanceof Integer i)
return "int: " + i;
else if (obj instanceof Double d)
return "double: " + d;
else if (obj instanceof String s)
return "str: " + s;
return "unknown";
}
String format(Object obj) {
return switch (obj) {
case Integer i -> "int: " + i;
case Double d -> "double: " + d;
case String s -> "str: " + s;
default -> "unknown";
};
}
Why the modern way wins
๐
Structured dispatch
Switch makes the branching structure explicit and scannable.
๐ฏ
Expression form
Returns a value directly โ no mutable variable needed.
โ
Exhaustiveness
The compiler ensures all types are handled.
Old Approach
if-else Chain
Modern Approach
Type Patterns
JDK Support
Pattern matching in switch
Available
Widely available since JDK 21 LTS (Sept 2023)
How it works
Pattern matching in switch lets you match on types directly, combining the type test, cast, and binding in one concise case label. The compiler checks completeness.
Related Documentation
Proof