Java switch with default, break, and multiple passes — what is the full output for z from 0 to 3?\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 < 4; z++) \n {\n switch (z) \n {\n case x: System.out.print("0 ");\n default: System.out.print("def ");\n case x-1: System.out.print("1 ");\n break;\n case x-2: System.out.print("2 ");\n }\n }\n }\n}\n\nSelect the correct sequence.

Difficulty: Medium

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

More Questions from Flow Control

Discussion & Comments

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