java.lang.arrayindexoutofboundsexception – How to handle Array Index Out Of Bounds Exception
In this post, we feature a comprehensive Example on How to handle Array Index Out Of Bounds Exception. Java supports the creation and manipulation of arrays, as a data structure. A bunch of Java data structures are implemented using arrays to store and expand their data. Thus, arrays are massively used in programming, as they provide a very fast and easy way to store and access pieces of data.
Each array consists of a concrete number of elements and thus, it has a fixed size. The index of an array is an integer value that resides in the interval [0, n-1]
, where n is the size of the matrix. If we request for an index that is either negative, or greater than or equal to the size of the array, an ArrayIndexOutOfBoundsException
is thrown.
The ArrayIndexOutOfBoundsException
is a RuntimeException
thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program.
For example, let’s carefully observe the following code snippet:
class Example { public static void main(String[] args) { char[] matrix = new char[] {'H', 'e', 'l', 'l', 'o'}; System.out.println(matrix); /* Print each letter of the char array in a separate line. */ for(int i = 0; i <= matrix.length; ++i) { System.out.println(matrix[i]); } } }
The above code snippet throws the following exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at main.java.Example.main(Example.java:10)
If we carefully observe the exception we will see that in line 10 of our code, we ask the matrix[5]
element. However, this element does not exist, as our matrix has size 5 and thus, a valid index resides in the interval [0, 4].
One more example that throws an ArrayIndexOutOfBoundsException
is the following:
import java.util.ArrayList; import java.util.List; class Example { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); /* The following statement produces an IndexOutOfBoundsException. */ System.out.println(list.get(2)); } }
The above code snippet throws the following exception:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
In this case, the exception is a little more descriptive and it is interpreted as follows:
- The
index
field denotes the position of the element that we requested for. - The
Size
field denotes the size of the matrix. - An ArrayList with a size of 2 has valid indices in the interval [0, 1].
- The exception is thrown because we requested for an invalid index. So, if we want to access the 2nd element of the list, we must write:
list.get(1);
because the 1st element of a
List
, as with arrays, starts at index 0.
Important: The ArrayIndexOutOfBoundsException
is a sub-class of the IndexOutOfBoundsException
.
Common error cases
The most common case is to declare an array with size “n” and access the n-th element. However, as we already mentioned, the indices of an array with size “n”, reside in the interval [0, n – 1] and thus, statements like:
char[] matrix = new char[5]; char[5] = ‘\n’;
throw an ArrayIndexOutOfBoundsException
.
Moreover, a common error case is found while iterating over the elements of an array, using a for loop
. The following statement is wrong:
for(int i = 0; i <= array.length; ++i) {
because in the last iteration, the value of i
equals to the length of the array and thus, it is not a valid index. The correct iteration with a for loop
is show below:
for(int i = 0; i < array.length; ++i) {
How to deal with the exception
Java is a safe programming language and won’t let you access an invalid index of an array. The internal data structures of Java, such as ArrayList
, contain methods that check if the requested index is actually valid or not. For example, in Java 7, the get
method of the ArrayList
class, contains the following check, before returning the required object:
rangeCheck(index);
which is implemented as:
private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
In order to avoid the exception, first, be very careful when you iterating over the elements of an array of a list. Make sure that your code requests for valid indices.
Second, consider enclosing your code inside a try-catch
statement and manipulate the exception accordingly. As mentioned, Java won’t let you access an invalid index and will definitely throw an ArrayIndexOutOfBoundsException
. However, be very careful inside the block of the catch
statement, because if you don’t handle the exception appropriately, you may conceal it and thus, create a bug in your application.
This was a tutorial on how to handle Array Index Out Of Bounds Exception (ArrayIndexOutOfBoundsException
).