1Z0-811 · Question #7
1Z0-811 Question #7: Real Exam Question with Answer & Explanation
The correct answer is D. do-while. Option D (do-while) is correct because a do-while loop executes its body at least once before checking the condition. When traversing an array in reverse, you initialize an index at arr.length - 1. For an empty array, this is -1, and the loop will still execute once, attempting a
Question
Options
- Aenhanced for
- Bstandard for
- Cwhile
- Ddo-while
Explanation
Option D (do-while) is correct because a do-while loop executes its body at least once before checking the condition. When traversing an array in reverse, you initialize an index at arr.length - 1. For an empty array, this is -1, and the loop will still execute once, attempting arr[-1] and throwing an ArrayIndexOutOfBoundsException - making it fundamentally unreliable for this task.
Why the distractors are wrong:
- A (enhanced for) - while it iterates forward, it can be used indirectly (e.g., pushing elements onto a stack then printing), so it is not disqualified outright.
- B (standard for) - easily handles reverse iteration:
for (int i = arr.length - 1; i >= 0; i--). - C (while) - also works: initialize outside, check condition before entering, decrement inside - it safely handles empty arrays by never entering the loop.
Memory tip: Think "Do-while = Does it No Matter What." Any loop that forces at least one execution is dangerous when zero iterations may be needed - and an empty array in reverse needs exactly zero iterations.
Topics
Community Discussion
No community discussion yet for this question.