The binding variable is in scope only where the test succeeded, so the compiler guarantees the cast is safe.
List<Object> values = List.of("java", 42, 3.5, List.of(1, 2));
for (Object o : values) {
if (o instanceof String s && s.length() > 3) {
System.out.println("long string: " + s.toUpperCase());
} else if (o instanceof Integer i) {
System.out.println("int doubled: " + (i * 2));
} else if (o instanceof List<?> l) {
System.out.println("list of size " + l.size());
} else {
System.out.println("other: " + o);
}
}
long string: JAVA
int doubled: 84
other: 3.5
list of size 2
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-30