57.7k views
1 vote
Which of the following loops would always cause an ArrayIndexOutOfBoundsException? Choose all that apply.

a) for (int i = 0; i < array.length; i++)
b) for (int i = 1; i <= array.length; i++)
c) for (int i = 0; i <= array.length; i++)
d) for (int i = 1; i < array.length; i++)

User Aiuspaktyn
by
7.5k points

1 Answer

3 votes

Final answer:

Loops 'b' and 'c' would always cause an ArrayIndexOutOfBoundsException because they attempt to access an array element one index beyond the last valid index, which in Java is from 0 to array.length - 1.

Step-by-step explanation:

The loops that would always cause an ArrayIndexOutOfBoundsException are the ones that try to access elements beyond the valid range of indices in an array. In Java, valid indices for an array range from 0 to array.length - 1. Loop 'b' with the condition for (int i = 1; i <= array.length; i++) causes an ArrayIndexOutOfBoundsException because it tries to access array[array.length], which is one index beyond the last valid index.

Similarly, loop 'c' for (int i = 0; i <= array.length; i++) will also cause the exception, for the same reason as loop 'b' when i equals array.length. On the other hand, loops 'a' and 'd' are safe and will not cause an exception because they do not exceed the array's bounds. Loop 'a' uses i < array.length and loop 'd' uses i < array.length starting at index 1.

User Jaap Haagmans
by
7.8k points