What is ArrayIndexOutOfBoundsException in Java?


An array is a data structure/container/object that stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation.

The position of the elements in the array is called an index or subscript. The first element of the array is stored at index 0 and, the second element is at index 1 and so on.

Each element in an array is accessed using an expression that contains the name of the array followed by the index of the required element in square brackets.

System.out.println(myArray[3]);
//prints 1457

Generally, an array is of fixed size and each element is accessed using the indices. For example, we have created an array with size 7. Then the valid expressions to access the elements of this array will be a[0] to a[6] (length-1).

Whenever you used an –ve value or, the value greater than or equal to the size of the array, then the ArrayIndexOutOfBoundsException is thrown.

For Example, if you execute the following code, it displays the elements in the array asks you to give the index to select an element. Since the size of the array is 7, the valid index will be 0 to 6.

Example

 Live Demo

import java.util.Arrays;
import java.util.Scanner;
public class AIOBSample {
   public static void main(String args[]){
      int[] myArray = {1254, 1458, 5687,1457, 4554, 5445, 7524};
      System.out.println("Elements in the array are: ");
      System.out.println(Arrays.toString(myArray));
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the index of the required element: ");
      int element = sc.nextInt();
      System.out.println("Element in the given index is :: "+myArray[element]);
   }
}

But if you observe the below output we have requested the element with the index 9 since it is an invalid index an ArrayIndexOutOfBoundsException raised and the execution terminated.

Output

Run time exception −

Elements in the array are:
[1254, 1458, 5687, 1457, 4554, 5445, 7524]
Enter the index of the required element:
7
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
   at AIOBSample.main(AIOBSample.java:12)
raja
Published on 15-Oct-2019 10:37:44
Advertisements