Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

when — an additional condition on a switch pattern

In Java SE 21, the contextual keyword when introduces an additional condition (a guard) after a case pattern in a switch statement or expression. The branch is selected only when the value matches the pattern and the guard evaluates to true.

Version: Language target: Java SE 21. Neither the repository runtime version nor the production runtime version is attested.

Syntax

case Pattern when Expression -> ...
case Pattern when Expression: ...

when is a contextual keyword, not a reserved keyword: it has this role in the Guard grammar, but can be an identifier outside that context. In Java SE 21, it introduces an additional condition after a case pattern in a switch statement or expression. It is neither a separate statement nor a replacement for if.

The pattern is tested first. Only after a match is the condition following when evaluated; it can use variables declared by that pattern, such as s. A result of true allows the branch to be selected; false continues the search for an applicable label. A guard can be used with either -> or :. It cannot be attached to a constant label such as case 42.

The guard must have type boolean or Boolean; unboxing a null value of type Boolean throws NullPointerException. A constant expression whose value is false is forbidden. Local variables and parameters used but not declared in the guard must be final or effectively final.

Place a more specific guarded case before a general case of the same type. Reversing that order in the example would cause a compile-time error because the guarded label would be dominated. case null explicitly handles null; default alone does not provide that handling. The example targets Java SE 21 and needs no preview features; it does not attest the repository runtime or production runtime version.

Examples

public class WhenExample {
    static String classify(Object value) {
        return switch (value) {
            case null -> "null";
            case String s when s.length() > 3 -> "long string";
            case String s -> "short string";
            default -> "other";
        };
    }

    public static void main(String[] args) {
        System.out.println(classify("Java"));
        System.out.println(classify("Hi"));
        System.out.println(classify(42));
        System.out.println(classify(null));
    }
}

Result

long string
short string
other
null

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources