ArrayIndexOutOfBoundsException in Java

In this blog post, we'll learn what is ArrayIndexOutOfBoundsException in Java, its typical causes, practical examples, and best practices to avoid ArrayIndexOutOfBoundsException.

What is ArrayIndexOutOfBoundsException? 

The ArrayIndexOutOfBoundsException is a runtime exception in Java. It is 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. 

ArrayIndexOutOfBoundsException Class Diagram

Common Causes

Looping Errors: Often occurs when looping through an array and the loop boundary exceeds the array length. 

Hard-Coded Indices: Hard coding an array index value without verifying if it's within bounds.

External Input: Accepting index values from external sources without proper validation.

Practical Examples and Outputs

1. Accessing Negative Index:

public class NegativeIndexDemo {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4};
        System.out.println(array[-1]);  // Negative index access
    }
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 4
	at NegativeIndexDemo.main(NegativeIndexDemo.java:4)

2. Off-by-One Error in Loop: 

The "off-by-one" error is one of the most common errors leading to this exception.

public class OffByOneDemo {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40};
        for (int i = 0; i <= numbers.length; i++) {
            System.out.println(numbers[i]);
        }
    }
}
Output:
10
20
30
40
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
	at OffByOneDemo.main(OffByOneDemo.java:6)

3. Multidimensional Arrays: 

It's not just one-dimensional arrays; multi-dimensional arrays can also throw this exception.

public class MultiDimensionalDemo {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        System.out.println(matrix[2][3]);  // This will throw an exception
    }
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at MultiDimensionalDemo.main(MultiDimensionalDemo.java:8)

4. Array Length Zero: 

Even if an array exists, it might have a length of zero, especially if it's dynamically populated.

public class ZeroLengthDemo {
    public static void main(String[] args) {
        int[] emptyArray = new int[0];
        System.out.println(emptyArray[0]);  // This will throw an exception
    }
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
	at ZeroLengthDemo.main(ZeroLengthDemo.java:5)

Mitigation and Best Practices 

Check array boundaries: Always verify the array's boundaries using its length attribute. 

Utilize the enhanced for loop: This loop automatically iterates over all array elements, preventing boundary violations.

Beware of dynamically populated arrays: If you're populating arrays based on data from databases, files, or APIs, always check the array's length before accessing its elements. 

Properly manage multi-dimensional arrays: Ensure all dimensions of your arrays are properly accounted for. 

Conclusion 

The ArrayIndexOutOfBoundsException can be a developer's nightmare but is easy to manage with a bit of caution. By being vigilant about the array's boundaries and following best practices, you can easily write efficient and error-free code in Java.

Comments