The instanceof pattern binds a typed variable, removing the explicit cast.
Object obj = "hello world";
if (obj instanceof String s && s.length() > 5) {
System.out.println("string of length " + s.length());
}
string of length 11
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