Question 1
What does the following program print? ```java public class Main { sealed interface Result permits Ok, Err {} record Ok(String value) implements Result {} non-sealed interface Err extends Result {} record BadInput(String message) implements Err {} public static void main(String[] args) { Result r = new Ok("done"); String out = switch (r) { case Ok ok -> ok.value(); case Err err -> "error"; }; System.out.println(out); } } ```
A. doneCorrect answer
`r` holds an `Ok` instance whose record component `value` is `"done"`. The switch matches `case Ok ok`, evaluates `ok.value()`, and assigns `"done"` to `out`, which is then printed. The code compiles without error: `Err` is a lawful `non-sealed` permitted subtype of the sealed `Result`, `BadInput` lawfully implements the `non-sealed` `Err` without appearing in any `permits` clause, and the switch is exhaustive because all direct permitted subtypes of `Result` are covered.
B. Compilation fails — `BadInput` does not appear in any `permits` clause
`BadInput` implements `Err`, which is declared `non-sealed`. A `non-sealed` permitted subtype intentionally reopens the hierarchy: any class or interface may extend or implement it without being listed in any `permits` clause. The compiler imposes no such requirement on `BadInput` (JEP 409).
C. Compilation fails — the switch expression is not exhaustive because `Err` is `non-sealed`
Exhaustiveness is evaluated over a sealed type's *direct* permitted subtypes, not over every concrete implementation that may exist at runtime. `Result` permits exactly `Ok` and `Err`; the switch covers both. A `case Err err` arm catches every value whose runtime type implements `Err`, so the switch is exhaustive regardless of how many unknown classes may implement the `non-sealed` `Err` (JLS §14.28.2).
D. error
`r` is constructed as `new Ok("done")`, an instance of `Ok`, not of any `Err` implementation. The switch matches the first arm (`case Ok ok`), not the second, so the string literal `"error"` is never evaluated.
Explanation
A `non-sealed` permitted subtype breaks out of the closed hierarchy on purpose: any class or interface may extend or implement it freely, with no obligation to appear in a `permits` clause, so `BadInput implements Err` is valid and raises no compilation error. Exhaustiveness of a switch expression over a sealed type is satisfied by covering every *direct* permitted subtype; a `case Err err` arm catches all implementations of `Err` at runtime, making the switch exhaustive even though `Err` is open for arbitrary extension. The runtime value `new Ok("done")` is not an `Err`, so the second arm is bypassed entirely and the program prints `done` (JEP 409; JLS §14.28.2).