Return to site

JAVA CERTIFICATION QUESTION: The arrow and colon delimiters in Java switch/case structures

· java

What’s the difference between these two delimiters—and when can they work together?

Given

enum Direction {
    UP, DOWN, HOLD;
}

 and

public static void main(String[] args) {
    var dir = Direction.UP;
    var where = switch(dir) {
        case UP -> "up";               // line n1
        case HOLD -> { yield "hold"; } // line n2
        case DOWN: yield "down";       // line n3
    };
    System.out.print(where);
}

 

Which is true? Choose one.

A. The syntax of line n1 is invalid in a switch expression.

B. The syntax of line n2 is invalid in a switch expression.

C. The syntax of line n3 is invalid in a switch expression.

D. The main method fails to compile for a reason not listed.

E. The main method compiles fine and prints up to console.