What happens if try to access an element with an index greater than the size of the array 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 as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on.

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

For example, if an array of 6 elements is created with name myArray, you can access the element of the array at index 3 as −

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

Creating an array in Java

In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −

int myArray[] = new int[7];
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;

Or, you can directly assign values with in flower braces separating them with commas (,) as −

int myArray = { 1254, 1458, 5687, 1457, 4554, 5445, 7524};

Accessing array elements greater than its size

Though, you can refer the elements of an array by using the name and index as −

myArray[5];

You cannot access the elements that are greater to the size of the array. i.e. If you create an array with 7 elements, as you observe in the diagram you can access up to myArray[6].

If you try to access the array position (index) greater than its size, the program gets compiled successfully but, at the time of execution it generates an ArrayIndexOutOfBoundsException exception.

Example

public class AccessingElements {
   public static void main(String[] args) {
      //Creating an integer array with size 5
      int inpuArray[] = new int[5];
      //Populating the array
      inpuArray[0] = 41;
      inpuArray[1] = 98;
      inpuArray[2] = 43;
      inpuArray[3] = 26;
      inpuArray[4] = 79;
      //Accessing index greater than the size of the array
      System.out.println( inpuArray[6]);
   }
}

Run time exception

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
   at myPackage.AccessingElements.main(AccessingElements.java:17)

Updated on: 02-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements