LearnFrenzy
Sign in Take a free test

Control Flow Statements · Predict the Output · Question 13

Deconstructing records in a switch Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 13 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links