Careeroza
Pattern Matching for switch
Switch on Types (Java 21)
switch can match type patterns, add conditions with when (guards), and handle case null. Cases are checked top to bottom, so put more specific cases first.
Example
public class Main {
static String classify(Object o) {
return switch (o) {
case null -> "null value";
case Integer i when i < 0 -> "negative int " + i;
case Integer i -> "int " + i;
case String s when s.isBlank() -> "blank string";
case String s -> "string '" + s + "'";
case int[] arr -> "int array of size " + arr.length;
default -> "other: " + o.getClass().getSimpleName();
};
}
public static void main(String[] args) {
Object[] inputs = { -5, 7, " ", "UPI", new int[]{1, 2, 3}, 2.5, null };
for (Object in : inputs) System.out.println(classify(in));
}
}Output
negative int -5 int 7 blank string string 'UPI' int array of size 3 other: Double null value
Rules
- A switch over
Objectneedsdefault; a switch over a sealed type does not if all subtypes are covered. - A case that can never match because an earlier case covers it (e.g.
case Integer ibeforecase Integer i when i > 0) is a compile error ("dominated"). - Without
case null, a null selector throwsNullPointerException, as before.