Traversing Arrays

AP Computer Science A· difficulty 3/5

int[] a = {10, 20, 30, 40};
for (int i = 0; i <= a.length; i++) {
  System.out.println(a[i]);
}

What happens?

  • A

    Compilation error

  • B

    ArrayIndexOutOfBoundsException after printing 10, 20, 30, 40

    check_circle
  • 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.

Want 10 more like this — adaptive to your weak spots?

Related questions