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.

Programmer DD
Programmer DD
Programmer DD
Simplify Java Type Checks: Using Pattern Matching with instanceof in Java 16

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.
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javatype checkingPattern MatchinginstanceofJava 16
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.