Java switch fall-through with constant short case labels — what sequence is printed?\n\npublic class Switch2 \n{\n final static short x = 2;\n public static int y = 0;\n public static void main(String [] args) \n {\n for (int z = 0; z < 3; z++) \n {\n switch (z) \n {\n case x: System.out.print("0 ");\n case x-1: System.out.print("1 ");\n case x-2: System.out.print("2 ");\n }\n }\n }\n}\n\nChoose the exact output.

Difficulty: Medium

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

More Questions from Flow Control

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion