java.lang.ArrayIndexOutOfBoundsException exception in JAVA

java.lang.ArrayIndexOutOfBoundsException exception in JAVA

Array index out of bound exception is an exception thrown when you try to access an index out of the array range. Let's assume the array size is 4 and you are trying to access an index equal or greater than 4.

public class ArrayIndexOutOfBoundsExceptionMain {

    public static void main(String args[]) {
        int[] arr = {1, 2};

        // This line will throw java.lang.ArrayIndexOutOfBoundsException
        System.out.println(arr[2]);

        //fixing: Compare the index with the size of the array
        int index = 4;
        if(index<arr.length) {
            System.out.println(arr[index]);
        }
    }

}