Simplify Java Type Checks: Using Pattern Matching with instanceof in Java 16
This article explains how the new pattern‑matching form of the instanceof operator introduced in Java 16 lets you both test an object's type and cast it in a single step, reducing boilerplate code compared to the traditional approach, with clear examples and tips.
The instanceof keyword is used to determine whether an object is an instance of a particular class.
Consider a map where values may be of different types, declared as Object:
Map<String, Object> data = new HashMap<>();
data.put("key1", "aaa");
data.put("key2", 111);When retrieving a value, you need to check its type before casting. The traditional way:
Object value = data.get("key1");
if (value instanceof String) {
String s = (String) value;
System.out.println(s.substring(1));
}Since Java 16, pattern matching for instanceof allows the type test and cast to be combined:
Object value = data.get("key1");
if (value instanceof String s) {
System.out.println(s.substring(1));
}This reduces boilerplate and makes the code clearer.
Tip: The feature went through two preview releases (JDK 14 JEP 305, JDK 15 JEP 375) before being finalized in JDK 16 JEP 394.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
