1. Introduction
When dealing with arrays in Java, ArrayIndexOutOfBoundsException is an exception you’ll most probably encounter. In this article, you’ll learn how to fix this exception. You’ll also learn some best practices for avoiding the ArrayIndexOutOfBoundsException.
2. What Java Says about ArrayIndexOutOfBoundsException
According to the Javadoc, an ArrayIndexOutOfBoundsException 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.
3. How to Reproduce
Let’s consider the following code which creates an integers array of size 5:
int[] arr = new int[5];
Arrays in Java are zero-indexed, meaning that the first element is at index 0 and the last element is at index arr.length - 1
. Any attempt to access an index out of this range will result in an ArrayIndexOutOfBoundsException.
int[] arr = new int[5];//array of size 5
int value = arr[5];//index 5 is not in range => ArrayIndexOutOfBoundsException
Running the above code snippet will print the following to the console:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at Scratch.main(scratch.java:4)
To fix the exception, you should make sure that the index is between 0 and 4 (which is 5 – 1).
int[] arr = new int[5];//array of size 5
int value = arr[4];//index 4 is in range => No ArrayIndexOutOfBoundsException
4. Best Practices to Avoid ArrayIndexOutOfBoundsException
4.1. Check array bounds
Always ensure that the index of the element you are trying to access is within the range [0, yourArray.length – 1].
int[] arr = new int[5];
int index = 5;
if (index >= 0 && index < arr.length) {//Boundaries check
int value = arr[index]; // Accessing element safely
} else {
// Handle out-of-bounds access gracefully
}
4.2. Use loops safely
When iterating an array using a loop, make sure that the start and end conditions of your loop are within the range of the array’s indexes.
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) { //Elements are within the range [0, arr.length - 1]
// Your code here
}
Always pay special attention to edge cases, since they’re the most frequent cause of ArrayIndexOutOfBoundsException
4.3. Prefer enhanced for-loop
Whenever possible, prefer using the enhanced for-loop. This way, you don’t have to worry about index boundaries.
int[] arr = new int[5];
for (int value : arr) { //No index => No potential ArrayIndexOutOfBoundsException
// Your code here
}
5. Conclusion
In this brief tutorial, you learned about the ArrayIndexOutOfBoundsException and how to fix it.
Pingback: How to Fix IndexOutOfBoundsException In Java