Java 21: Pattern matching for switch

Switch can match on type patterns, replacing long if-else instanceof chains.

Code
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);
Output
int 42
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