CKTIS / Java
switch — multi-way selection
switch — multi-way selection: A Switch expression selects a value among case labels; arrow rules written case ... -> do not fall through and in Java 21 support patterns and when guards.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
switchA Switch expression selects a value among case labels; arrow rules written case ... -> do not fall through and in Java 21 support patterns and when guards.
Use a Switch expression with arrow rules for exhaustive mapping of an enum or sealed hierarchy; a multi-statement rule returns its value with yield.
Classic colon labels may fall through without break, and pattern order is constrained by dominance; default does not replace an explicit case null for a null selector.
A Switch expression must be exhaustive; changing a binary sealed hierarchy without recompiling may cause MatchException, and all branches determine the result type.
Arrow rules in the Switch expression select a guarded Integer, a String pattern, and explicit case null, yielding int:3, text:2, and null.
Examples
public class Main {
static String describe(Object value) {
return switch (value) {
case null -> "null";
case Integer i when i > 0 -> "int:" + i;
case String s -> "text:" + s.length();
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(describe(3));
System.out.println(describe("hi"));
System.out.println(describe(null));
}
}
Result
int:3 text:2 null
Arrow rules in the Switch expression select a guarded Integer, a String pattern, and explicit case null, yielding int:3, text:2, and null.