Generally speaking, preventing ArrayIndexOutOfBoundsException
can be done by simply making sure that the index is within the bound.
All arrays are 0-origin. An array with length n
can be indexed by the integers 0
to n-1
.
Thus, a simple check like this is quite typical:
if (i >= 0 && i < arr.length) {
System.out.println(arr[i]);
}
Barring nasty things like arr
getting reassigned between the check and the access, the above code will NEVER throw ArrayIndexOutOfBoundsException
.
2D array "boards"
Often, you can be a lot more specific, e.g. when you have rectangular "boards" stored in a two-dimensional array (or rather, array of arrays in Java).
final int M = 10; // height, i.e. number of rows
final int N = 8; // width, i.e. number of columns
final int[][] board = new int[M][N];
Then you can have a method like the following:
boolean isInBound(int r, int c) {
return (r >= 0) && (r < M) && (c >= 0) && (c < N);
}
The bound check is both easier to read and to write, since we know that we have an MxN board. If isInBound(r, c)
, then board[r][c]
will NEVER throw ArrayIndexOutOfBoundsException
.