Guarded patterns with when
Add conditions to pattern cases using when guards.
Code Comparison
✕ Java 8
if (shape instanceof Circle c) {
if (c.radius() > 10) {
return "large circle";
} else {
return "small circle";
}
} else {
return "not a circle";
}
✓ Java 21+
return switch (shape) {
case Circle c
when c.radius() > 10
-> "large circle";
case Circle c
-> "small circle";
default -> "not a circle";
};
Why the modern way wins
Precise matching
Combine type + condition in a single case label.
Flat structure
No nested if/else inside switch cases.
Readable intent
The when clause reads like natural language.
Old Approach
Nested if
Modern Approach
when Clause
Since JDK
21
Difficulty
intermediate
JDK Support
Guarded patterns with when
Available
Widely available since JDK 21 LTS (Sept 2023)
How it works
Guarded patterns let you refine a type match with an additional boolean condition. This keeps all the branching logic in the switch instead of nesting if statements inside cases.