ArrayIndexOutOfBoundsException in java

ArrayIndexOutOfBoundsException class is available in java.lang package and it extends IndexOutOfBoundsException class. It is an Unchecked Exception.


public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException



ArrayIndexOutOfBoundsException class inherits methods from java.lang.Object class and java.lang.Throwable class.

Hierarchy of ArrayIndexOutOfBoundsException




When ArrayIndexOutOfBoundsException Occurs


An ArrayIndexOutOfBoundsException has thrown when an array has been inserted values or accessed out of an array size index.
For example, an array size is 5 [0th to 4th index], but we inserted out of array size index i.e, 5th index.

Example:



package com.exceptions;
public class AIOBExceptionTest {
       public static void main(String[] args) {
              int[] arr=new int[5];
              arr[0]=10;
              arr[1]=20;
              arr[2]=30;
              arr[3]=40;
              arr[4]=50;
              arr[5]=60;   //ArrayIndexOutOfBoundsException
       }
}


Output:



Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
       at com.exceptions.AIOBExceptionTest.main(AIOBExceptionTest.java:10)



10
20
30
40
50
60 -- Out of array size
      0             1               2                3                 4               5
An array size is 5 [0th to 4th index], but we inserted in the 5th index also i.e, out of array size index.

While accessing array



package com.exceptions;
public class AIOBExceptionTest {
       public static void main(String[] args) {
              int[] arr=new int[5];
              arr[0]=10;
              arr[1]=20;
              arr[2]=30;
              arr[3]=40;
              arr[4]=50;          
              for(int i=0;i<=arr.length;i++){
                     System.out.println(arr[i]);  //java.lang.ArrayIndexOutOfBoundsException
              }                         
       }
}


Output:



10
20
30
40
50
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
       at com.exceptions.AIOBExceptionTest.main(AIOBExceptionTest.java:11)


In this program, we accessed out of array size using for loop
Inserted values in exact array size

10
20
30
40
50
    0            1                 2                3           4

While accessing using for loop, we accessed out of array size index i.e, 5th index.
arr.length= 5 [0th to 4th  index] but for loop repeated 0th to 5th times

10
20
30
40
50
Out of array size
      0             1              2                 3                4               5


To avoid this we should write i<=arr.length-1 or i<arr.length in for loop


No comments:

Post a Comment