Java switch with default, break, and multiple passes — what is the full output for z from 0 to 3? public class Switch2 { final static short x = 2; public static int y = 0; public static void main(String [] args) { for (int z = 0; z < 4; z++) { switch (z) { case x: System.out.print("0 "); default: System.out.print("def "); case x-1: System.out.print("1 "); break; case x-2: System.out.print("2 "); } } } } Select the correct sequence.
-
A0 def 1
-
B2 1 0 def 1
-
C2 1 0 def def
-
D2 1 0 def 1 def 1
Answer
Correct Answer: 2 1 0 def 1 def 1
Explanation
Introduction / Context:This problem tests how default behaves when reached (with or without a match) and how break truncates fall-through. You must trace four iterations of z and respect the textual order of cases.
Given Data / Assumptions:
- x = 2 → cases are 2, default, 1 (with break), and 0.
- Loop z iterates 0, 1, 2, 3.
- Only the case for 1 has a break; others fall through.
Concept / Approach:On a match, execution starts at that case and continues forward. If no case matches, execution starts at default and continues forward. The break after printing "1 " stops further fall-through for that iteration.
Step-by-Step Solution:
z = 0 → matches case (x-2) at the bottom; prints "2 " (no further statements) → "2 ".z = 1 → matches case (x-1); prints "1 " then break → "1 ".z = 2 → matches case x; prints "0 " then default "def " then case (x-1) "1 " then break → "0 def 1 ".z = 3 → no match; start at default: print "def " then case (x-1) prints "1 " then break → "def 1 ".Concatenate: "2 1 0 def 1 def 1".Verification / Alternative check:Removing the break after case (x-1) would allow fall-through into case (x-2), changing the sequence.
Why Other Options Are Wrong:
- They omit required parts of fall-through or misplace default participation.
Common Pitfalls:Believing default executes only when no case matches; it also falls through to later cases unless a break stops it.
Final Answer:2 1 0 def 1 def 1