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 — Pattern matching in switch | java.evolved
Language
Intermediate
Pattern matching in switchReplace 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";
};
}
See a problem with this code? Let us know.
Why the modern way wins
📐
Structured dispatchSwitch makes the branching structure explicit and scannable. 🎯
Expression formReturns a value directly — no mutable variable needed. ✅
ExhaustivenessThe 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. Related Documentation
Proof
Related patterns
Language
Beginner
Pattern matching for instanceofJava 8
if (obj instanceof String) {
String s = (String) obj;
int length = s.length();
// do something with 'length'
}
Java 16+
if (obj instanceof String s) {
int length = s.length();
// do something with 'length'
}
JDK 16+
→
Language
Beginner
Unnamed variables with _Java 8
try {
parse(input);
} catch (Exception ignored) {
log("parse failed");
}
map.forEach((key, value) -> {
process(value); // key unused
});
Java 22+
try {
parse(input);
} catch (Exception _) {
log("parse failed");
}
map.forEach((_, value) -> {
process(value);
});
JDK 22+
→
Language
Beginner
Records for data classesJava 8
public class Point {
private final int x, y;
public Point(int x, int y) { ... }
public int getX() { return x; }
public int getY() { return y; }
// equals, hashCode, toString
}
Java 16+
public record Point(int x, int y) {}
JDK 16+
→
|
| 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. |