Question 1
One of the `User` values passed to `f` carries a null `Name` component. What is the result of running this program? ```java public class Main { record Name(String first, String last) {} record User(Name name, int age) {} static String f(Object o) { return switch (o) { case User(Name(var first, _), var age) when age >= 18 -> "adult:" + first; case User(Name n, _) -> "minor:" + n.last(); case null, default -> "none"; }; } public static void main(String[] args) { System.out.println(f(new User(new Name("Ann", "Lee"), 20)) + "|" + f(new User(null, 30)) + "|" + f(new User(new Name("Bo", "Kim"), 12))); } } ```
A. Throws NullPointerExceptionCorrect answer
A nested record pattern never matches a null component, so the user with a null name skips the guarded case, but the following nested type pattern is unconditional, binds the null, and calling a method on it throws NullPointerException.
B. adult:Ann|none|minor:Kim
Assumes the user with a null name falls through to the default; the unconditional type pattern matches it and then dereferences null.
C. adult:Ann|minor:null|minor:Kim
Assumes the unconditional type pattern also rejects null; a type pattern of the component's declared type performs no null check, so it binds null.
D. Compilation fails
Assumes the patterns or the unnamed pattern are illegal; record patterns, type patterns, and the unnamed pattern are all valid, so it compiles.
Explanation
A nested record pattern includes an implicit null check and does not match a null component, whereas a nested type pattern whose type is the component's declared type is unconditional and binds even a null value without testing it. Routing a null component into an unconditional type pattern therefore binds null, and using that binding throws at run time. The unnamed pattern matches any component without binding it.