Switch can match on type patterns, replacing long if-else instanceof chains.
Object obj = 42;
String desc = switch (obj) {
case Integer i -> "int " + i;
case String s -> "string " + s;
case null -> "null";
default -> "other";
};
System.out.println(desc);
int 42
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