Developing Algorithms Using ArrayLists

AP Computer Science A· difficulty 4/5

int[] a = {1, 2, 3, 4, 5};
for (int i = 1; i < a.length; i++) {
  a[i] = a[i + 1];
}

What happens?

  • A

    ArrayIndexOutOfBoundsException

    check_circle
  • B

    Prints 1 3 4 5 5

  • C

    Prints 1 2 3 4 5

  • D

    Compilation error

Explanation

The condition should be i < a.length - 1 to avoid accessing a[a.length]. As written, when i = 4, a[5] is out of bounds.

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

Related questions