Skip to main content
Java 16 · Topic 2 of 3

Pattern matching for instanceof

Definition​

Pattern matching for instanceof (Java 16) checks a type and gives you a typed variable in one step. You no longer need a separate cast after the check.

Example code​

No cast after instanceof

class Demo {
static String describe(Object value) {
if (value instanceof String s && s.length() > 3) { // s is a String right here
return "long text: " + s.toUpperCase();
} else if (value instanceof Integer i) {
return "number plus one: " + (i + 1);
}
return "something else";
}

public static void main(String[] args) {
System.out.println(describe("hello"));
System.out.println(describe(41));
System.out.println(describe("hi"));
}
}

// Output:
// long text: HELLO
// number plus one: 42
// something else

Finished this page? Track your progress (saved only in your browser).