for Loops

AP Computer Science A· difficulty 2/5

public static int sumAll(int[] a) {
    int total = 0;
    for (int i = 0; i <= a.length; i++) {
        total += a[i];
    }
    return total;
}

What error occurs when this method runs?

  • A

    NullPointerException on the first iteration

  • B

    ArrayIndexOutOfBoundsException on the last iteration

    check_circle
  • C

    There is no error

  • D

    The method returns one less than the correct sum

Explanation

Valid indices are 0 through a.length-1. Using <= a.length attempts to access a[a.length], which throws ArrayIndexOutOfBoundsException.

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

Related questions