nerdexam
Oracle

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…

Controlling Program Flow

Question

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 -> System.out.println("Not a valid rank."); } What is the result?

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)
  • A
    11% (2)
  • B
    6% (1)
  • C
    83% (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 without break
  • 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 switch with : 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 add break unless intentional.

Topics

#switch expressions#pattern matching#multiple case labels#arrow syntax

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice