Instanceof

1 post in this section

Pattern Matching for instanceof (JEP 394): Smarter Type Checks

Finalized in Java 16 (JEP 394). Available in all Java 16+ releases, including Java 17. Previous previews: Java 14 (JEP 305) and Java 15 (JEP 375). The Problem: The instanceof-Cast Dance Every Java developer has written this pattern: // Java 11 — check, then cast if (obj instanceof String) { String s = (String) obj; // cast is logically redundant System.out.println(s.toUpperCase()); } The instanceof check already verified the type. The cast on the next line is conceptually redundant — the compiler could infer that obj is a String in the if body.

Continue reading »