Skip to content

Java ArrayIndexOutOfBoundsException Example

Ramesh Fadatare edited this page Jul 12, 2019 · 2 revisions

This Java example demonstrates the usage of java.lang.ArrayIndexOutOfBoundsException class with an example.

java.lang.ArrayIndexOutOfBoundsException has thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Java ArrayIndexOutOfBoundsException Example

In this example, if an array is having only 3 elements and we are trying to display -1 or 4th element then it would throw this exception.

package com.javaguides.corejava;

public class ArrayIndexOutOfBounds {

    public static void main(String[] args) {

        int[] nums = new int[] {
            1,
            2,
            3
        };

        try {
            int numFromNegativeIndex = nums[-1]; // Trying to access at negative index
            int numFromGreaterIndex = nums[4]; // Trying to access at greater index
            int numFromLengthIndex = nums[3]; // Trying to access at index equal to size of the array
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("ArrayIndexOutOfBoundsException caught");
            e.printStackTrace();
        }
    }
}

Output

ArrayIndexOutOfBoundsException caught
java.lang.ArrayIndexOutOfBoundsException: -1
	at com.javaguides.corejava.ArrayIndexOutOfBounds.main(ArrayIndexOutOfBounds.java:10)
Clone this wiki locally