2D Arrays: Creation and Access

AP Computer Science A· difficulty 4/5

int[][] m = {{1, 2, 3}, {4, 5, 6}};
int sum = 0;
for (int r = 0; r <= m.length; r++) {
    for (int c = 0; c < m[r].length; c++) {
        sum += m[r][c];
    }
}
System.out.println(sum);

What is the result?

  • A

    15

  • B

    6

  • C

    21

  • D

    ArrayIndexOutOfBoundsException

    check_circle

Explanation

The off-by-one r <= m.length allows r to reach 2, so m[r].length attempts to access m[2] which does not exist (only 2 rows). This throws ArrayIndexOutOfBoundsException. This is the classic bounds-check bug.

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

Related questions