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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
