Effects of the ArrayIndexOutOfBoundsException
When an ArrayIndexOutOfBoundsException is thrown & not caught, it will cause the Java program to terminate abruptly. This means any code after the point where the exception occurred will not be executed.
Consider this example:
int[] numbers = {1, 2, 3};
System.out.println("Before exception");
int x = numbers[3]; // Throws ArrayIndexOutOfBoundsException
System.out.println("After exception");

You can also try this code with Online Java Compiler
Run Code
The output will be:
Before exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Main.main(Main.java:4)
As you can see, the program crashes after the exception is thrown & the line "After exception" is never printed.
In a more complex program, an uncaught ArrayIndexOutOfBoundsException can leave the system in an inconsistent state. Resources may not be properly closed, data may be only partially updated, or the user may be left seeing an error message rather than the expected output.
Therefore, it's crucial to handle ArrayIndexOutOfBoundsExceptions appropriately.
In order to solve this, we might take care of below mentioned steps :
- Checking array bounds before accessing elements
- Using try-catch blocks to catch & handle the exception
- Providing default values or alternative logic when an out of bounds access is attempted
You're right, we can expand on the causes further. Here's an updated version of that section:
Causes of the ArrayIndexOutOfBoundsException
There are several reasons why an ArrayIndexOutOfBoundsException might be thrown:
1. Negative Index
Arrays in Java are zero-indexed, meaning the first element is at index 0, not 1. Attempting to access an array with a negative index will throw an ArrayIndexOutOfBoundsException. For example:
int[] numbers = {1, 2, 3};
int x = numbers[-1]; // Throws ArrayIndexOutOfBoundsException
2. Index >= Array Length
Each array in Java has a fixed length. Accessing an index that is greater than or equal to this length will cause an ArrayIndexOutOfBoundsException. Remember, for an array of length n, the valid indices are 0 to n-1. For example:
int[] numbers = {1, 2, 3};
int x = numbers[3]; // Throws ArrayIndexOutOfBoundsException
3. Incorrect Loop Conditions
ArrayIndexOutOfBoundsExceptions often occur when iterating over arrays. If the loop condition is not correctly defined, it might attempt to access elements outside the array bounds. For example:
int[] numbers = {1, 2, 3};
for (int i = 0; i <= numbers.length; i++) {
System.out.println(numbers[i]); // Throws ArrayIndexOutOfBoundsException on last iteration
}
4. Using the Wrong Index Variable
Using the wrong variable as an array index can lead to ArrayIndexOutOfBoundsExceptions. This might happen when you have multiple index variables in your code. For example:
int[] numbers = {1, 2, 3};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[j]); // Uses j instead of i, potentially causing ArrayIndexOutOfBoundsException
}
5. Not Checking Array Bounds
When accessing array elements based on user input or data from an external source, it's important to validate the indices first. Failing to do so can result in ArrayIndexOutOfBoundsExceptions. For example:
int[] numbers = {1, 2, 3};
Scanner scanner = new Scanner(System.in);
int index = scanner.nextInt();
int x = numbers[index]; // If user enters an out-of-bounds index, throws ArrayIndexOutOfBoundsException
6. Modifying Array Length
In Java, arrays have a fixed length that is set when they are created. Attempting to change the length of an array after creation can lead to ArrayIndexOutOfBoundsExceptions. For example:
int[] numbers = {1, 2, 3};
numbers[3] = 4; // Tries to add an element at index 3, throws ArrayIndexOutOfBoundsException
Example of ArrayIndexOutOfBoundsException
Suppose we're writing a program to calculate the average of a student's test scores. The scores are stored in an array, & the program asks the user which score they want to exclude from the average.
Here's how the code will look
int[] scores = {85, 90, 92, 88, 91};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the index of the score to exclude: ");
int excludeIndex = scanner.nextInt();
int sum = 0;
for (int i = 0; i < scores.length; i++) {
if (i != excludeIndex) {
sum += scores[i];
}
}
double average = sum / (scores.length - 1);
System.out.println("Average excluding score at index " + excludeIndex + ": " + average);
If the user enters 2, the program will exclude the score at index 2 (which is 92) & calculate the average of the remaining scores. The output will be:
Average excluding score at index 2: 88.5
However, if the user enters an index that's out of bounds, say 7, an ArrayIndexOutOfBoundsException will be thrown:
Enter the index of the score to exclude: 7
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5
at Main.main(Main.java:11)
This happens because the scores array has a length of 5, so valid indices are 0 to 4. Trying to access scores[7] throws an exception.
To handle this, we could add a check before using the user-provided index:
if (excludeIndex < 0 || excludeIndex >= scores.length) {
System.out.println("Invalid index. Please enter a number between 0 & " + (scores.length - 1));
} else {
// Calculate average
}
This way, if the user enters an invalid index, they'll see a friendly error message instead of the program crashing with an exception.
Constructors of ArrayIndexOutOfBoundsException
The ArrayIndexOutOfBoundsException class provides several constructors that allow you to create instances of this exception with different levels of detail. Understanding these constructors can be useful when you want to throw an ArrayIndexOutOfBoundsException yourself or when you're catching & handling this exception.
1. ArrayIndexOutOfBoundsException(): This is the default constructor. It creates an ArrayIndexOutOfBoundsException without any detail message. For example:
throw new ArrayIndexOutOfBoundsException();
2. ArrayIndexOutOfBoundsException(int index): This constructor accepts the illegal index that caused the exception. It creates an exception with a detail message that includes this index. For example:
throw new ArrayIndexOutOfBoundsException(5);
This would create an exception with the message "Index 5 out of bounds for length 4" (assuming the array length was 4).
3. ArrayIndexOutOfBoundsException(String s): This constructor accepts a custom detail message as a String. It allows you to provide more context about the exception. For example:
throw new ArrayIndexOutOfBoundsException("Tried to access element at index " + i);
4. ArrayIndexOutOfBoundsException(int sourceLength, int index): This constructor is a bit more specialized. It's used in the internal implementation of some Java classes. The sourceLength parameter is the length of the array, & index is the illegal index that was attempted. For example:
throw new ArrayIndexOutOfBoundsException(4, 5);
This would create an exception with the message "Index 5 out of bounds for length 4".
In most cases, you'll probably use the default constructor or the one that accepts a custom message. The other constructors are less commonly used but can be handy in certain situations.
When catching an ArrayIndexOutOfBoundsException, you can use the getMessage() method to retrieve the detail message associated with the exception, regardless of which constructor was used to create it.
How to Avoid ArrayIndexOutOfBoundsException?
While it's important to know how to handle ArrayIndexOutOfBoundsExceptions when they occur, it's even better to avoid them altogether. Let’s discuss some of the methods to prevent this exception in your Java code:
1. Check Array Bounds: Before accessing an array element, always check that the index is within the valid range. You can do this with a simple if statement:
if (index >= 0 && index < array.length) {
// Access array[index]
}
2. Use Array.length: When iterating over an array, use the length property in your loop condition to ensure you don't go out of bounds. For example:
for (int i = 0; i < array.length; i++) {
// Access array[i]
}
3. Be Careful with User Input: If you're using user input to determine which array element to access, always validate the input first. Ensure it's a valid index before using it:
int index = getUserInput();
if (index >= 0 && index < array.length) {
// Access array[index]
} else {
System.out.println("Invalid index!");
}
4. Use Try-Catch Blocks: If you're not sure whether an index will be valid or not, you can use a try-catch block. This allows your program to handle the exception gracefully if it occurs:
try {
// Access array[index]
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
}
5. Use the Enhanced For Loop: If you just need to iterate over all elements in an array & don't need the index, use an enhanced for loop (also known as a "for-each" loop). This eliminates the possibility of an ArrayIndexOutOfBoundsException:
for (int element : array) {
// Access element
}
6. Use Utilities Like Arrays.copyOfRange(): If you need a subarray from an array, use utility methods like Arrays.copyOfRange() instead of trying to extract the subarray manually. These methods handle bounds checking for you.
int[] subArray = Arrays.copyOfRange(array, startIndex, endIndex);
How to Resolve ArrayIndexOutOfBoundsException?
Even after best efforts to avoid ArrayIndexOutOfBoundsExceptions, they can still occur, especially when dealing with complex codes or due to unexpected inputs. When you face with this exception, here are few methods by which you can try to resolve it:
1. Read the Exception Message: The first step is to carefully read the exception message. It will tell you which index was attempted & the length of the array. This information is crucial for identifying where the problem occurred. For example:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
This tells us that the code tried to access index 5 on an array of length 4.
2. Locate the Line of Code: The exception message will also include a stack trace that shows the line of code where the exception was thrown. Look for the line in your code file. If the exception occurred in a library or framework method, look at the lines in your code that call that method.
at MyClass.myMethod(MyClass.java:10)
This indicates that the exception occurred on line 10 of MyClass.java in the myMethod method.
3. Inspect the Index & Array Length: Once you've found the relevant code, check how the index is calculated & where the array comes from. Ensure that the index is within the bounds of the array. Remember, valid indices are from 0 to length-1.
// If index comes from a variable
if (index < 0 || index >= array.length) {
// Handle invalid index
}
4. Handle Edge Cases: Consider edge cases that could lead to invalid indices. For example, what happens if the array is empty? What if the user enters a negative number? Add checks to handle these scenarios.
if (array.length == 0) {
System.out.println("Array is empty!");
} else {
// Access array elements
}
5. Use Debugging Tools: If the cause of the exception is still unclear, use debugging tools to step through the code line by line. Watch how variables change & when the exception gets thrown. This can provide valuable insights.
6. Add Exception Handling: Once you've identified & fixed the root cause of the ArrayIndexOutOfBoundsException, consider adding exception handling to your code. This way, if the exception occurs again (perhaps due to unexpected input), your program can handle it gracefully instead of crashing.
try {
// Code that might throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
// Handle the exception, e.g., use a default value or prompt user for new input
}
Handling ArrayIndexOutOfBoundsException
When an ArrayIndexOutOfBoundsException occurs, it's important to handle it appropriately to prevent your program from crashing. Few ways to handle this exception are:
1. Using try-catch Block
The most common way to handle an exception is by using a try-catch block. You can enclose the code that might throw an ArrayIndexOutOfBoundsException inside a try block & catch the exception in the catch block. For example:
try {
int[] numbers = {1, 2, 3};
int x = numbers[5]; // Throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
// Handle the exception, e.g., use a default value or log the error
}
2. Checking Array Bounds
Another way to handle ArrayIndexOutOfBoundsExceptions is to check the array bounds before accessing an element. You can use an if statement to ensure the index is within the valid range:
int[] numbers = {1, 2, 3};
int index = 5;
if (index >= 0 && index < numbers.length) {
int x = numbers[index];
// Use x
} else {
System.out.println("Invalid index: " + index);
// Handle the invalid index, e.g., use a default value or prompt for new input
}
3. Using a Default Value
If an ArrayIndexOutOfBoundsException occurs & you don't need to execute any specific error handling code, you can simply provide a default value. This is useful when you know what value to use if the requested index is out of bounds.
int[] numbers = {1, 2, 3};
int index = 5;
int defaultValue = 0;
int x = (index >= 0 && index < numbers.length) ? numbers[index] : defaultValue;
// Use x, which will be the value at numbers[index] if index is valid, or defaultValue if not
Frequently Asked Questions
What is the difference between ArrayIndexOutOfBoundsException & IndexOutOfBoundsException?
ArrayIndexOutOfBoundsException is a more specific exception that is thrown when an invalid index is used to access an array. IndexOutOfBoundsException is a more general exception that is the superclass of ArrayIndexOutOfBoundsException. It can be thrown by other classes as well, such as String & ArrayList, when an invalid index is used.
Can I catch an ArrayIndexOutOfBoundsException using a catch block for Exception?
Yes, since ArrayIndexOutOfBoundsException is a subclass of Exception, you can catch it using a catch block for Exception. However, it's generally better to catch the most specific exception possible. This makes your code more readable & helps with debugging.
How can I find the specific index that caused an ArrayIndexOutOfBoundsException?
The exception message of an ArrayIndexOutOfBoundsException includes the index that caused the exception. You can access this message using the getMessage() method. Alternatively, you can also catch the exception & print the stack trace, which will show you the line of code where the exception occurred.
Conclusion
In this article, we have discussed the ArrayIndexOutOfBoundsException in Java. We learned what causes this exception, like accessing an array with an invalid index. We also saw how to avoid it using techniques like bounds checking & exception handling. We discussed methods for resolving the exception when it occurs, like reading the error message & debugging.
You can also check out our other blogs on Code360.