1Z0-829 · Question #8
Given: public class Test { public static void main(String[] args) { final int x = 2; int y = x; while (y<3) { switch (y) { case 0+x: y++; case 1: y++; } } System.out.println(y); } } What is the…
The correct answer is E. Compilation fails. There is an issue with this answer key. The stated correct answer E is actually incorrect per the Java Language Specification, and this is worth understanding precisely so you don't get tripped up. Why E is wrong: final int x = 2 makes x a compile-time constant variable (JLS…
Question
Options
- A4
- B2
- C6
- DNothing is printed because of an indefinite loop.
- ECompilation fails.
- F5
- GA runtime exception is thrown.
- H3
How the community answered
(34 responses)- A6% (2)
- C12% (4)
- D3% (1)
- E62% (21)
- G18% (6)
Explanation
There is an issue with this answer key. The stated correct answer E is actually incorrect per the Java Language Specification, and this is worth understanding precisely so you don't get tripped up.
Why E is wrong: final int x = 2 makes x a compile-time constant variable (JLS §4.12.4 - a final primitive initialized with a constant expression). Therefore case 0+x: is a valid compile-time constant expression equal to case 2:. The compiler evaluates it at compile time; this is not ambiguous.
What actually happens (correct answer: A - prints 4):
y = x = 2, while conditiony < 3is true, enter loop.switch(2): matchescase 0+x:(=case 2:), executesy++→ y=3.- No
break, falls through tocase 1:, executesy++→ y=4. while(4 < 3)is false, exits. Prints4.
Why each distractor is wrong:
- B/H (2/3): Ignores the fall-through from
case 2intocase 1. - D (infinite loop): y reaches 4 and exits normally.
- F/C (5/6): Fall-through only fires once per switch entry; y can't go past 4 here.
- G (runtime exception): Nothing here throws - no bad cast, null, or divide-by-zero.
Memory tip: When you see case expr: on an exam, ask two questions: (1) Is the expression a compile-time constant? (2) Are there duplicate case values? A final local variable initialized from a literal is a constant - this distinguishes final int x = 2 (valid in case) from int x = 2 (not valid).
Bottom line for exam prep: If this question appears on your actual exam and E is marked correct, the question itself has an error. The real trap being attempted here is testing whether you know
finalmakes a variable usable incaselabels - but the question accidentally has a valid constant expression, making E wrong.
Topics
Community Discussion
No community discussion yet for this question.