Java 21: Guarded patterns with when

Add a when clause to a switch case to refine matching with a boolean guard.

Code
Object obj = 150;
String size = switch (obj) {
    case Integer i when i < 100 -> "small";
    case Integer i when i < 1000 -> "medium";
    case Integer i -> "large";
    default -> "n/a";
};
System.out.println(size);
Output
medium
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