Java 16: Pattern matching for instanceof

The instanceof pattern binds a typed variable, removing the explicit cast.

Code
Object obj = "hello world";
if (obj instanceof String s && s.length() > 5) {
    System.out.println("string of length " + s.length());
}
Output
string of length 11
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26