Pattern matching in switch
Replace if-else instanceof chains with clean switch type patterns.
Code Comparison
✕ Java 8
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";
}
✓ Java 21+
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
Since JDK
21
Difficulty
intermediate
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.