Java switch without breaks (fall-through) — compute final j value.\n\npublic class Test \n{ \n public static void main(String args[]) \n { \n int i = 1, j = 0; \n switch(i) \n { \n case 2: j += 6; \n case 4: j += 1; \n default: j += 2; \n case 0: j += 4; \n } \n System.out.println("j = " + j); \n } \n}\n\nWhat is printed?

Difficulty: Easy

Correct Answer: j = 6

Explanation:


Introduction / Context:
This MCQ reinforces switch fall-through semantics in Java when break statements are omitted. You must determine which labels execute when no case matches i=1 until default is reached.



Given Data / Assumptions:

  • Switch expression is i = 1.
  • Cases present: 2, 4, default, and 0, with no breaks.
  • j starts at 0.


Concept / Approach:
If no case matches, execution begins at default and proceeds downward until the switch block ends (fall-through). Therefore, default and all following case bodies execute sequentially.



Step-by-Step Solution:

No match for case 2 or case 4.Hit default: j += 2 → j = 2.Fall through to case 0: j += 4 → j = 6.End of switch; print "j = 6".


Verification / Alternative check:
Add breaks after default or case 0 to change the result; with current code, both default and case 0 run.



Why Other Options Are Wrong:

  • "0", "2", or "4" ignore the second addition from case 0 or the first addition at default.


Common Pitfalls:
Expecting that default stops execution; it does not without a break.



Final Answer:
j = 6

More Questions from Flow Control

Discussion & Comments

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