Question 431
arr is a non-null int array (possibly empty).
int i = 0;
while (i < arr.length && arr[i] != 0)
{
i = i + 1;
}
Which of the following statements about the loop is true for every valid value of arr?Main Solution
Answer
Answer: A. Short-circuit evaluation of && guarantees the bound check i < arr.length is performed before the index arr[i]. The loop terminates either because i reached arr.length (no exception, since indexing was skipped), or because arr[i] equaled 0 (the index i was valid). Option C fails for an empty array; option B is wrong precisely because of short-circuit evaluation; option D is wrong because reaching the end of the array also terminates the loop.
Answer: Correct: A
A
After the loop, either i == arr.length or arr[i] == 0, and no exception is thrown.
B
If arr.length == 0, the loop throws an ArrayIndexOutOfBoundsException.
C
The loop body always executes at least once.
D
The loop terminates only if arr contains a zero.
Answer images

