nerdexam
Oracle

1Z0-809 · Question #107

Given: ``java public class Calculator { public static void main(String[] args) { int num = 5; int sum; do { sum += num; } while ( (num--) > 1); System.out.println("The sum is " + sum + "."); } } ``…

The correct answer is E. Compilation fails. Compilation fails because sum is declared as a local variable (int sum;) but never initialized before being read in sum += num. In Java, unlike instance fields (which default to 0), local variables have no default value - the compiler enforces explicit initialization and will…

Question

Given:
public class Calculator {
 public static void main(String[] args) {
 int num = 5;
 int sum;
 do {
 sum += num;
 } while ( (num--) > 1);
 System.out.println("The sum is " + sum + ".");
 }
}
What is the result?

Options

  • AThe sum is 2
  • BThe sum is 14
  • CThe sum is 15
  • DThe loop executes infinite times
  • ECompilation fails

How the community answered

(19 responses)
  • B
    5% (1)
  • C
    5% (1)
  • D
    11% (2)
  • E
    79% (15)

Explanation

Compilation fails because sum is declared as a local variable (int sum;) but never initialized before being read in sum += num. In Java, unlike instance fields (which default to 0), local variables have no default value - the compiler enforces explicit initialization and will throw a "variable sum might not have been initialized" compile-time error before the program can run.

Options A, B, C, and D are all runtime-level answers that assume the code compiles, which it never does. If sum were correctly initialized to 0, the do-while loop would add 5+4+3+2+1 = 15 (C), because the post-decrement num-- checks the current value before decrementing, so the body still runs when num=1 (where 1 > 1 is false and the loop exits after that iteration). B (14) is the off-by-one trap for misreading post-decrement, and D (infinite loop) is wrong because num steadily decreases until the condition fails.

Memory tip: Think "local = lonely" - local variables get no automatic initialization; they must be explicitly assigned before use, or the compiler refuses to proceed.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice