Java / Java 21 Coding Standards Interview Questions
How does pattern matching for switch change the coding standard for type-checking code?
Before pattern matching, a type-dispatch chain was typically written as a series of instanceof checks with explicit casts inside an if/else if ladder, and nothing forced the author to handle every known subtype.
// old style if (shape instanceof Circle) { Circle c = (Circle) shape; return Math.PI * c.radius() * c.radius(); } else if (shape instanceof Square) { Square s = (Square) shape; return s.side() * s.side(); } // Java 21 style, exhaustive over a sealed type return switch (shape) { case Circle c -> Math.PI * c.radius() * c.radius(); case Square s -> s.side() * s.side(); };
The standard now favors the switch form specifically when the type being matched is sealed, because the compiler then verifies at compile time that every permitted subtype has a case - a new shape added to the permits clause without a matching case is a compile error rather than a silent runtime gap.
This shifts type-dispatch bugs from "discovered when the missing branch runs in production" to "caught the moment the new subtype is added", which is the core reason teams are told to prefer sealed hierarchies with switch over open instanceof ladders for closed domains.
More Related questions...