J.VII · Java 25 practice question
What does the following Java 25 program print when switching over a `sealed` hierarchy?
sealed interface Shape permits Circle, Square {}
record Circle(int r) implements Shape {}
record Square(int s) implements Shape {}
void main() {
Shape shape = new Square(5);
int val = switch (shape) {
case Circle c -> c.r();
case Square sq -> sq.s() * sq.s();
};
System.out.println(val);
}
Check answer and explanation
Correct answer: 25
Explanation
`shape` is a `Square(5)`, so `case Square sq` matches and computes `5 * 5`, printing `25`.
Common trap
`5` is the side length and `10` is `5 + 5`, whereas the action computes `sq.s() * sq.s()`.
Source: JEP 441: Pattern Matching for switch — Summary
Checked against the cited text on 2026-11-27.