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…
Question
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)- A3% (1)
- C7% (2)
- D90% (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
Community Discussion
No community discussion yet for this question.