nerdexam
Oracle

1Z0-808 · Question #60

Given the following main method: public static void main(String[] args) { int num = 5; do { System.out.print(num-- + " "); } while (num == 0); } What is the result?

The correct answer is D. 5. D is correct because a do-while loop always executes its body once before checking the condition. The body prints num--, which outputs 5 (post-decrement: print first, then decrement), leaving num at 4. The condition num == 0 evaluates 4 == 0, which is false, so the loop exits…

Using Loop Constructs

Question

Given the following main method: public static void main(String[] args) { int num = 5; do { System.out.print(num-- + " "); } while (num == 0); } What is the result?

Options

  • A5 4 3 2 1 0
  • B5 4 3 2 1
  • C4 2 1
  • D5
  • ENothing is printed

How the community answered

(29 responses)
  • A
    3% (1)
  • C
    7% (2)
  • D
    90% (26)

Explanation

D is correct because a do-while loop always executes its body once before checking the condition. The body prints num--, which outputs 5 (post-decrement: print first, then decrement), leaving num at 4. The condition num == 0 evaluates 4 == 0, which is false, so the loop exits immediately - printing only 5.

A and B would require the condition to be num >= 0 or num > 0 respectively, allowing the loop to continue while num stays positive. C doesn't correspond to any plausible loop behavior here. E would be correct if this were a regular while loop (where the condition is checked first), but do-while guarantees at least one execution regardless of the condition.

Memory tip: Think of do-while as "do it first, ask questions later" - the condition only matters after the first run, so the body always fires at least once.

Topics

#do-while loops#post-decrement operator#loop condition evaluation#control flow

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice