Language intermediate

Guarded patterns with when

Add conditions to pattern cases using when guards.

✕ Java 8
if (shape instanceof Circle c) {
    if (c.radius() > 10) {
        return "large circle";
    } else {
        return "small circle";
    }
} else {
    return "not a circle";
}
✓ Java 21+
return switch (shape) {
    case Circle c
        when c.radius() > 10
            -> "large circle";
    case Circle c
            -> "small circle";
    default -> "not a circle";
};
🎯

Precise matching

Combine type + condition in a single case label.

📐

Flat structure

No nested if/else inside switch cases.

📖

Readable intent

The when clause reads like natural language.

Old Approach
Nested if
Modern Approach
when Clause
Since JDK
21
Difficulty
intermediate
Guarded patterns with when
Available

Widely available since JDK 21 LTS (Sept 2023)

How it works

Guarded patterns let you refine a type match with an additional boolean condition. This keeps all the branching logic in the switch instead of nesting if statements inside cases.

Share 𝕏 🦋 in