J.VII · Java 25 practice question

Consider the following sealed class hierarchy in Java 25: ```java sealed interface Shape permits Circle, Square {} record Circle(double radius) implements Shape {} record Square(double side) implements Shape {} public static void processShape(Shape shape) { String match = switch (shape) { case Circle(double r) -> "Circle of radius " + r; case Square(double s) -> "Square with side " + s; }; System.out.println(match); } ``` Which statement accurately describes how pattern matching with records functions within a sealed hierarchy in Java 25?

Choose one answer
Check answer and explanation

Correct answer: The `case` expressions automatically enforce exhaustiveness checking against all declared subtypes of `Shape`, and an explicit `default` case is optional if all subtypes are handled.

Explanation

Java 25 extends pattern matching to sealed hierarchies, leveraging the guarantee that the compiler knows all possible subtypes. For sealed types, the compiler enforces exhaustiveness; if you miss a declared subtype, compilation fails, treating it as a requirement for a catch-all or error handling if the compiler allows it, but the primary strength here is the enforced completeness check for known subtypes. In practice, when exhaustiveness is guaranteed, the compiler often treats missing cases as errors unless a `default` branch handles the unhandled cases.

Common trap

Option A is tempting because exhaustiveness is key, but Option C is more precise regarding the compiler's behavior enforcement coupled with the structure of sealed types in this context.

Source: Java Language Specification documentation regarding pattern matching and sealed types. (Specific JEP reference is needed for exact 25 behavior, linking to the general pattern matching documentation is the best proxy.) https://docs.oracle.com/en/java/javas
Checked against the cited text on 2026-11-27.

Report an error in this question