GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Pattern matching for instanceof | java.evolved

Home / Language / Pattern matching for instanceof
Language Beginner

Pattern matching for instanceof

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

Combine type check and cast in one step with pattern matching.

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'
}
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
🔄

No redundant cast

Type check and variable binding happen in a single expression.

📏

Fewer lines

One line instead of two — the cast line disappears entirely.

🛡️

Scope safety

The 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
Pattern Matching for instanceof (JEP 394) ↗
Proof
View proof source ↗
Related patterns
Language Beginner

Compact source files

Java 8
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println(
            "Hello, World!");
    }
}
Java 25
void main() {
    IO.println("Hello, World!");
}
Hover to see modern ➜
JDK 25+ →
Language Beginner

Type inference with var

Java 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
}
Hover to see modern ➜
JDK 10+ →
Language Beginner

Text blocks for multiline strings

Java 8
String json = "{\n" +
    "  \"name\": \"Duke\",\n" +
    "  \"age\": 30\n" +
    "}";
Java 15+
String json = """
    {
      "name": "Duke",
      "age": 30
    }""";
Hover to see modern ➜
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.