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 for instanceof | java.evolved
Language
Beginner
Pattern matching for instanceofCombine type check and cast in one step with pattern matching. Code Comparison
✕ Java 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'
}
See a problem with this code? Let us know.
Why the modern way wins
🔄
No redundant castType check and variable binding happen in a single expression. 📏
Fewer linesOne line instead of two — the cast line disappears entirely. 🛡️
Scope safetyThe pattern variable is only in scope where the type is guaranteed. Old Approach
instanceof + Cast
Modern Approach
Pattern Variable
Since JDK
16
Difficulty
Beginner
JDK Support
Pattern matching for instanceof
Available
Widely available since JDK 16 (March 2021) How it works
Pattern matching for instanceof eliminates the redundant cast after a type check. The variable is automatically scoped to where the pattern matches, making code safer and shorter. Related Documentation
Proof
Related patterns
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+
→
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
Text blocks for multiline stringsJava 8
String json = "{\n" +
" \"name\": \"Duke\",\n" +
" \"age\": 30\n" +
"}";
Java 15+
String json = """
{
"name": "Duke",
"age": 30
}""";
JDK 15+
→
|
| 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. |