Question 13
Back to Exercise
What is the output of the following Java program?
public class Main {
record Point(int x, int y) {}
static String where(Point p) {
return switch (p) {
case Point(int x, int y) when x == 0 && y == 0 -> "origin";
case Point(int x, int y) when x == 0 -> "y-axis";
case Point(int x, int y) when y == 0 -> "x-axis";
case Point(int x, int y) when x == y -> "diagonal";
case Point(int x, int y) -> "(" + x + "," + y + ")";
};
}
public static void main(String[] args) {
Point[] pts = {new Point(0, 0), new Point(0, 4), new Point(3, 3), new Point(2, 0), new Point(1, 5)};
for (Point p : pts) System.out.print(where(p) + " ");
System.out.println();
}
}
- A origin y-axis diagonal x-axis (1,5) Correct
- B origin x-axis diagonal y-axis (1,5)
- C origin y-axis (3,3) x-axis (1,5)
- D origin origin diagonal x-axis (1,5)
Correct Answer: Option A
Record patterns bind the components directly; cases are tried top to bottom, so the order of guards matters.
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!