Open In App

java.lang.ArrayIndexOutOfBoundsExcepiton in Java with Examples

Last Updated : 02 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The java.lang.ArrayIndexOutOfBoundsException is a runtime exception and thrown only at the execution state of the program. Java compiler never checks for this error during compilation. 

The java.lang.ArrayIndexOutOfBoundsException is one of the most common exceptions in java. It occurs when the programmer tries to access the value of an element in an array at an invalid index. This Exception is introduced in Java from JDK Version 1.0 onwards. ArrayIndexOutOfBoundsException can occur due to many reasons like when we try to access the value of an element in the array at a negative index or index greater the size of array -1.

Below are the Code Examples showing the cases in which this error can occur and errors are handled and displayed using try-catch block.

Case 1:- Accessing The Value Of An Element At An Negative Index

Java




// Java program to show the ArrayIndexOutOfBoundsException
// while accessing element at negative index
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        try {
            int array[] = new int[] { 4, 1, 2, 6, 7 };
            // accessing element at index 2
            System.out.println("The element at index 2 is "
                               + array[2]);
            // accessing element at index -1
            // this will throw the
            // ArrayIndexOutOfBoundsException
            System.out.println("The element at index -1 is "
                               + array[-1]);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Output

The element at index 2 is 2
java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5

Case 2:- Accessing The Element At Index Greater Then Size of Array -1

Java




// Java program to show the ArrayIndexOutOfBoundsException
// while accessing element at index greater then size of
// array -1
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        try {
            int array[] = new int[] { 4, 1, 2, 6, 7 };
            // accessing element at index 4
            System.out.println("The element at index 4 is "
                               + array[4]);
            // accessing element at index 6
            // this will throw the
            // ArrayIndexOutOfBoundsException
            System.out.println("The element at index 6 is "
                               + array[6]);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Output

The element at index 4 is 7
java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads