GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev — Guarded patterns with when | java.evolved
Language
Intermediate
Guarded patterns with whenAdd conditions to pattern cases using when guards. Code Comparison
✕ Java 8
if (shape instanceof Circle) {
Circle c = (Circle) shape;
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";
};
See a problem with this code? Let us know.
Why the modern way wins
🎯
Precise matchingCombine type + condition in a single case label. 📐
Flat structureNo nested if/else inside switch cases. 📖
Readable intentThe 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. Related Documentation
Proof
Related patterns
Language
Intermediate
Record patterns (destructuring)Java 8
if (obj instanceof Point) {
Point p = (Point) obj;
int x = p.getX();
int y = p.getY();
System.out.println(x + y);
}
Java 21+
if (obj instanceof Point(int x, int y)) {
IO.println(x + y);
}
JDK 21+
→
Language
Beginner
Type inference with varJava 8
Map<String, List<Integer>> map =
new HashMap<String, List<Integer>>();
for (Map.Entry<String, List<Integer>> e
: map.entrySet()) {
// verbose type noise
}
Java 10+
var map = new HashMap<String, List<Integer>>();
for (var entry : map.entrySet()) {
// clean and readable
}
JDK 10+
→
Language
Beginner
Compact source filesJava 8
public class HelloWorld {
public static void main(String[] args) {
System.out.println(
"Hello, World!");
}
}
Java 25
void main() {
IO.println("Hello, World!");
}
JDK 25+
→
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |