nerdexam
Oracle

1Z0-819 · Question #154

Given: public class Test { private int sum; public int compute() { int x = 0; while(x < 3) { sum += x++; } return sum; } public static void main(String[] args) { Test t = new Test(); int sum =…

The correct answer is D. 6. D (6) is correct because sum is an instance variable that persists between calls - after the first t.compute(), this.sum equals 3 (0+1+2). The second call starts with this.sum already at 3, then adds 0+1+2 again, returning 6, which is what gets printed. C (3) is wrong because…

Controlling Program Flow

Question

Given: public class Test { private int sum; public int compute() { int x = 0; while(x < 3) { sum += x++; } return sum; } public static void main(String[] args) { Test t = new Test(); int sum = t.compute(); sum = t.compute(); System.out.println(sum); } } What is the result?

Options

  • A9
  • BAn exception is thrown at runtime.
  • C3
  • D6

How the community answered

(22 responses)
  • A
    5% (1)
  • B
    5% (1)
  • C
    14% (3)
  • D
    77% (17)

Explanation

D (6) is correct because sum is an instance variable that persists between calls - after the first t.compute(), this.sum equals 3 (0+1+2). The second call starts with this.sum already at 3, then adds 0+1+2 again, returning 6, which is what gets printed.

C (3) is wrong because it assumes only the first compute() call matters, missing that the instance variable sum is stateful and carries over into the second call.

A (9) is a trap designed to catch students who lose track of what accumulates - there's no scenario in this code that produces 9; it's there to snag those who double-count or misread the loop boundary.

B is wrong because the code is syntactically and semantically valid - no null dereferences, no out-of-bounds access, no division by zero.

Memory tip: When you see a local variable in main with the same name as an instance field (int sum vs private int sum), that's a red flag - the local variable doesn't reset the instance field, so instance state silently accumulates across method calls.

Topics

#Post-increment operator#Instance variables#Loop state#Variable scope

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice