nerdexam
Oracle

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…

Controlling Program Flow

Question

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 result?

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)
  • A
    6% (2)
  • C
    12% (4)
  • D
    3% (1)
  • E
    62% (21)
  • G
    18% (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):

  1. y = x = 2, while condition y < 3 is true, enter loop.
  2. switch(2): matches case 0+x: (= case 2:), executes y++ → y=3.
  3. No break, falls through to case 1:, executes y++ → y=4.
  4. while(4 < 3) is false, exits. Prints 4.

Why each distractor is wrong:

  • B/H (2/3): Ignores the fall-through from case 2 into case 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 final makes a variable usable in case labels - but the question accidentally has a valid constant expression, making E wrong.

Topics

#switch statements#final variables#constant expressions#compilation

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice