1Z0-829 · Question #9
Given the code fragment: Integer rank = 4; switch (rank) { case 1,4 -> System.out.println("Range1"); case 5,8 -> System.out.println("Range2"); case 9,10 -> System.out.println("Range3"); default ->…
The correct answer is C. Range 1 Range 2 Range 3 Not a valida rank. Option C would only be correct if the code used traditional colon-style case labels (:) without break statements - in that scenario, Java's fall-through behavior would cause execution to continue through every subsequent case after the match, printing all four lines. However…
Question
Options
- ARange 1 Range 2 Range 3
- BRange1 Not a valid rank.
- CRange 1 Range 2 Range 3 Not a valida rank
- DRange 1
- ENot a valida rank
How the community answered
(18 responses)- A11% (2)
- B6% (1)
- C83% (15)
Explanation
Option C would only be correct if the code used traditional colon-style case labels (:) without break statements - in that scenario, Java's fall-through behavior would cause execution to continue through every subsequent case after the match, printing all four lines. However, the code as written uses arrow (->) case labels, introduced in Java 14, which execute exactly one branch and never fall through. This means rank = 4 matches case 1,4, prints "Range1", and exits - making D ("Range1") the logically correct answer.
Why each distractor fails:
- A & C assume fall-through prints all cases - only true without
->and withoutbreak - B would require a second match hitting
default, which is impossible in switch - E would only print if no case matched at all
Note to exam takers: There appears to be an error in this question. The marked answer C describes fall-through behavior from traditional
switchwith:labels, but the code uses->(arrow) syntax which prevents fall-through by design. If you see->on an exam switch block, the rule is: one branch, no fall-through, no break needed. If you see:, remember: fall-through is the default - always addbreakunless intentional.
Topics
Community Discussion
No community discussion yet for this question.