Java / Java 21 Interview Questions
How does Pattern Matching for switch work in Java 21?
JEP 441 finalises pattern matching in switch expressions and statements, extending the type-test patterns introduced in Java 16 (instanceof) to the full switch construct. It eliminates long chains of if-else instanceof casts and brings exhaustiveness checking to the compiler.
sealed interface Shape permits Circle, Rectangle, Triangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double w, double h) implements Shape {}
record Triangle(double base, double height) implements Shape {}
// Pattern matching switch expression
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.w() * r.h();
case Triangle t -> 0.5 * t.base() * t.height();
// No default needed — sealed hierarchy is exhaustive
};
}
// Guarded patterns — 'when' clause adds a boolean condition
static String classify(Object obj) {
return switch (obj) {
case Integer i when i < 0 -> "Negative int";
case Integer i when i == 0 -> "Zero";
case Integer i -> "Positive int: " + i;
case String s when s.isEmpty() -> "Empty string";
case String s -> "String: " + s;
case null -> "null value";
default -> "Other: " + obj;
};
}
// Dominance rule: more specific patterns must come first
// case Integer i when i < 0 must precede case Integer iThree important rules in Java 21 pattern switch:
- Exhaustiveness: the compiler checks that all possible input values are covered; missing a subtype of a sealed class is a compile error, not a runtime problem.
- Guarded patterns (
whenclause): replaces the old&&idiom inside case blocks. - Null handling: a
case nullarm can be written explicitly; without it a null input still throwsNullPointerExceptionas before.
More Related questions...