int[] a = {10, 20, 30, 40};
for (int i = 0; i <= a.length; i++) {
System.out.println(a[i]);
}What happens?
- A
Compilation error
- Bcheck_circle
ArrayIndexOutOfBoundsException after printing 10, 20, 30, 40
- C
Prints nothing
- D
Prints 10, 20, 30, 40 with no error
Explanation
The condition i <= a.length is the classic off-by-one bug. After printing all four elements, i=4 and a[4] throws ArrayIndexOutOfBoundsException. The correct condition is i < a.length.