Java switch fall-through with constant short case labels — what sequence is printed? public class Switch2 { final static short x = 2; public static int y = 0; public static void main(String [] args) { for (int z = 0; z < 3; z++) { switch (z) { case x: System.out.print("0 "); case x-1: System.out.print("1 "); case x-2: System.out.print("2 "); } } } } Choose the exact output.
-
A0 1 2
-
B0 1 2 1 2 2
-
C2 1 0 1 0 0
-
D2 1 2 0 1 2
Answer
Correct Answer: 2 1 2 0 1 2
Explanation
Introduction / Context:This problem exercises switch fall-through behavior across a loop. The case labels are compile-time constants derived from a final short x, allowing x, x-1, and x-2 to be legal case expressions.
Given Data / Assumptions:
- x = 2, so cases are 2, 1, and 0 in that textual order.
- No break statements appear; fall-through applies.
- Loop variable z runs 0, 1, 2.
Concept / Approach:For each z, execution begins at the matching case label (if any) and then falls through to the end of the switch, executing all subsequent print statements in order.
Step-by-Step Solution:
z = 0 → matches case 0 (x-2) only → prints "2 ".z = 1 → matches case 1 (x-1) → prints "1 " then falls into case 0 printing "2 " → total "1 2 ".z = 2 → matches case 2 (x) → prints "0 " then "1 " then "2 " → total "0 1 2 ".Concatenate across iterations: "2 1 2 0 1 2".Verification / Alternative check:Add break after each case to see "2 1 0" instead; current omission is deliberate to test fall-through.
Why Other Options Are Wrong:
- They place numbers in the wrong order or include/omit fall-through wrongly.
Common Pitfalls:Assuming the order of case labels in source must be numeric order—execution starts at the match and proceeds downward regardless of numeric value.
Final Answer:2 1 2 0 1 2