FAQ - james-bern/CS136 GitHub Wiki

FAQ

ArrayIndexOutOfBoundsException

Background

  • An array has a fixed number of slots; the number of slot's is the arrays' length.
  • In Java, arrays are zero-indexed; this means we start indexing the array at 0.

Explanation

  • An index must satisfy the array's bounds $0 \leq i \leq (\texttt{array.length - 1})$.
    • We can also write the bounds as $0 \leq i < \texttt{array.length}$.
  • An index that does not satisfy the bounds is "out of bounds."

Example

xxxxxx xxxxxx xxxxxx xxxxxx xxxxxx
foo[0] foo[1] foo[2] foo[3] foo[4]
  • int[] foo = new int[5]; has length 5.
  • We can index into the array with foo[0], foo[1], foo[2], foo[3], and foo[4].
  • The only valid indexes into foo are 0, 1, 2, 3, and 4.
  • foo[5] will throw an ArrayIndexOutOfBoundsException.
  • foo[42] will throw an ArrayIndexOutOfBoundsException.
  • foo[-1] will throw an ArrayIndexOutOfBoundsException.