Question 20
Back to Exercise
What is the output of the following Java program?
record Address(String city, String pin) { }
record Customer(String name, Address address) { }
public class Main {
static String region(Object o) {
return switch (o) {
case Customer(var name, Address(var city, var pin)) when pin.startsWith("4") -> name + " (west, " + city + ")";
case Customer(var name, Address(var city, var pin)) when pin.startsWith("1") -> name + " (north, " + city + ")";
case Customer(var name, Address a) -> name + " (other)";
default -> "not a customer";
};
}
public static void main(String[] args) {
System.out.println(region(new Customer("Asha", new Address("Pune", "411001"))));
System.out.println(region(new Customer("Ravi", new Address("Delhi", "110001"))));
System.out.println(region(new Customer("Meena", new Address("Chennai", "600001"))));
System.out.println(region(42));
}
}
- A Asha (west, Pune) Ravi (north, Delhi) Meena (other) not a customer Correct
- B Asha (other) Ravi (other) Meena (other) not a customer
- C Asha (west, Pune) Ravi (north, Delhi) Meena (west, Chennai) not a customer
- D Compilation error
Correct Answer: Option A
Nested record patterns pull out the inner Address components in one step.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!