ArrayIndexOutOfBoundsException in Java

ArrayIndexOutOfBoundsException in Java

An ArrayIndexOutOfBoundsException is a common runtime exception in Java that occurs when we try to access an element of an array using an invalid index. The valid index range for an array in Java is from 0 to array.length - 1.

For example, if we have an array with a length of 5, the valid indices are 0, 1, 2, 3, and 4. Trying to access any index outside this range will result in an ArrayIndexOutOfBoundsException.

Following is an example code that demonstrates how this exception can occur:

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        try {
            // Accessing the 6th element of the array, which doesn't exist
            int element = numbers[5];
            System.out.println("Element: " + element);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Error: Index 5 out of bounds for length 5

In the example above, the array numbers has a length of 5, so its valid indices range from 0 to 4. When we try to access numbers[5], we go beyond the valid range, and Java throws an ArrayIndexOutOfBoundsException.

To avoid this exception, we have to make sure to always use valid indices when accessing elements in an array. We can use conditions or loops to ensure that we stay within the array bounds.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments