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.
The
ArrayIndexOutOfBounds
exception is a run-time exception. Java’s compiler does not check for this error during compilation.
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 ; however, since indexing starts from , the loop must finish at index , 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 elements in myList
, which means that the last element is at index . Since myList.get(3)
attempts to access an element at index , 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.
Free Resources