What is the ArrayIndexOutOfBounds exception in Java?

Java, like other languages, supports the creation and manipulation of an array. The ArrayIndexOutOfBounds exception is thrown if a program tries to access an array index that is negative, greater than, or equal to the length of the array.

svg viewer

The ArrayIndexOutOfBounds exception is a run-time exception. Java’s compiler does not check for this error during compilation.

Code

The following code snippet demonstrates the error that results from a user attempting to index to an array location that does not exist.

class Program {
public static void main( String args[] ) {
int arr[] = {1, 3, 5, 2, 4};
for (int i=0; i<=arr.length; i++)
System.out.println(arr[i]);
}
}

​The length of arr is 55; however, since indexing starts from 00, the loop must finish at index 44, which holds the last element of the array. The exception is thrown when the loop attempts to index into arr[5] which does not exist.

Consider the next example, which uses an ArrayList​:

import java.util.ArrayList;
class Program {
public static void main( String args[] ) {
ArrayList<String> myList = new ArrayList<String>();
myList.add("Dogs");
myList.add("are");
myList.add("cute.");
System.out.println(myList.get(3));
}
}

The reason for this error is similar to the reason for the last one. There are 33 elements in myList, which means that the last element is at index 22. Since myList.get(3) attempts to access an element at index 33, the exception is thrown.

While the best way to avoid this exception is to always remain within the bounds of an array, it can be overlooked sometimes. The use of a try-catch block will catch the exception and ensure that the program does not exit.

Copyright ©2024 Educative, Inc. All rights reserved