Skip to main content
Java 21 (LTS) · Topic 2 of 4

Pattern matching for switch

Definition​

Pattern matching for switch (Java 21) lets a switch choose code by the type of a value, and even add a condition with when. It also handles null as a case.

Example code​

A switch that picks code by type and condition

class Demo {
static String describe(Object value) {
return switch (value) {
case null -> "nothing";
case Integer i when i > 100 -> "a big number: " + i; // type plus a condition
case Integer i -> "a number: " + i;
case String s -> "text of length " + s.length();
default -> "something else";
};
}

public static void main(String[] args) {
System.out.println(describe(500));
System.out.println(describe(7));
System.out.println(describe("java"));
System.out.println(describe(null));
System.out.println(describe(2.5));
}
}

// Output:
// a big number: 500
// a number: 7
// text of length 4
// nothing
// something else

Finished this page? Track your progress (saved only in your browser).