nerdexam
Oracle

1Z0-811 · Question #2

Given the code fragment: boolean checkOut = true; int days = 0; while (checkOut) { days++; if (days > 3) { checkOut = false; } } System.out.print (days); What is the result?

The correct answer is B. 4. B (4) is correct because days increments before the condition is checked - so when days reaches 4, the condition days > 3 is finally true, checkOut is set to false, the loop exits, and 4 is printed. A (2) is wrong because the loop runs far more than two iterations - it only…

Control Flow

Question

Given the code fragment: boolean checkOut = true; int days = 0; while (checkOut) { days++; if (days > 3) { checkOut = false; } } System.out.print (days); What is the result?

Options

  • A2
  • B4
  • CThe program executes an infinite number of times.
  • D3

How the community answered

(29 responses)
  • A
    14% (4)
  • B
    76% (22)
  • C
    3% (1)
  • D
    7% (2)

Explanation

B (4) is correct because days increments before the condition is checked - so when days reaches 4, the condition days > 3 is finally true, checkOut is set to false, the loop exits, and 4 is printed.

A (2) is wrong because the loop runs far more than two iterations - it only exits once days exceeds 3, not when it equals 2. D (3) is a common trap: the condition is days > 3 (strictly greater than), not days >= 3, so the loop does not stop at 3. C (infinite loop) is wrong because checkOut is eventually set to false once days > 3, giving the loop a guaranteed exit.

Memory tip: When you see > in an exit condition like days > 3, the variable must pass the threshold - think "the loop needs one extra step to cross the line," making the final value one higher than the number in the condition (3 + 1 = 4).

Topics

#while loop#loop termination#conditional statements#control flow

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice