Question 1
What is the output of the following program? ```java public class Main { public static void main(String[] args) { int x = 1; switch (x) { case 1 -> System.out.println("alpha"); case 2 -> System.out.println("beta"); default -> System.out.println("gamma"); } } } ```
A. alphaCorrect answer
Arrow-case labels carry an implicit no-fall-through guarantee. Only case 1 matches x == 1; its body executes and control exits the switch statement immediately — no subsequent arm is reached (JEP 361).
B. alpha beta
Assumes arrow labels fall through like traditional colon-label cases. With arrow labels, fall-through never occurs — only the matched arm executes, and no break statement is required or relevant.
C. alpha beta gamma
Assumes all arms execute for every selector value. A switch evaluates exactly the matched arm and exits the construct; the default arm executes only when no case label matches, not unconditionally.
D. Compilation fails
Arrow labels were standardised by JEP 361 (finalised in Java 14) and are valid in switch statements as well as switch expressions. The code is syntactically and semantically correct under Java 21.
Explanation
Arrow-case labels (the -> form) never fall through: exactly the matched arm executes, and control immediately exits the switch construct without any break statement (JEP 361). This is the fundamental behavioural difference from traditional colon-label cases, which fall through to successive arms unless explicitly broken. A switch evaluates only the matched arm; unmatched arms — including default when another case matches — are skipped entirely. Expecting multiple consecutive arms to fire conflates the two switch syntaxes. Arrow labels are valid in both switch statements and switch expressions since Java 14, so the code compiles cleanly.