Array Index Out Of Bounds Exception in Java

ArrayIndexOutOfBoundsException in Java is a runtime exception that occurs when an attempt is made to access an array element using an invalid index. The valid index range for an array is [0, n-1], where n represents the size of the array. If an index is negative or equal to or greater than n, Java throws an ArrayIndexOutOfBoundsException. This exception is exclusively generated at runtime and helps prevent unintended memory access beyond the defined array boundaries. In this blog, you are going to learn about Java’s ArrayIndexOutOfBoundsException in detail, along with its causes, prevention, and best practices

Table of Contents:

What is ArrayIndexOutOfBoundsException in Java

An array is a collection of similar types of data. It is the base for many advanced data structures, e.g., a list or a binary tree. It  stores the elements in a contiguous memory location, and it can also have multiple dimensions  

The java.lang.ArrayIndexOutOfBoundsException is a runtime exception and is thrown when the program is being executed. The Java compiler never checks for this error during the compilation process. 

The java.lang.ArrayIndexOutOfBoundsException is among the most frequently occurring exceptions in Java. This exception is caused when the developer attempts to retrieve the value of an element from an array beyond an invalid index. This Java Exception was introduced in Java from JDK Version 1.0 onwards. It can occur due to many reasons, like when we try to access the value of an element in the array at a negative index or an index greater than the size of the array.

Causes of ArrayIndexOutOfBoundsException in Java

The ArrayIndexOutOfBoundsException in Java occurs when an invalid index is used to access an element in an array. Below are some common causes of it:

1. Accessing a Negative Index

In Java, array indices must always be positive. If an attempt is made to access an element having a negative index, an ArrayIndexOutOfBoundsException will occur.  

For example:

Java

Output:  

 Accessing a Negative Index

2. Accessing Index Greater Than or Equal to the Array’s Length

The correct indexes for an array are in between 0 to array.length – 1. If an index is greater than or equal to the array’s size is accessed, then an ArrayIndexOutOfBoundsException will occur. 

For example:

Java

Output:  

Accessing Index Greater Than or Equal to the Array's Length

3. Accessing an Element Beyond the End of a Multi-Dimensional Array

Similar to one-dimensional arrays, multi-dimensional arrays also have limits. If an index exceeds the dimensions of any of the arrays, an exception will be thrown.

For example:

Java

Output:  

Accessing an Element Beyond the End of a Multi-Dimensional Array
Master Java Today - Accelerate Your Future
Enroll Now and Transform Your Future
quiz-icon

4. Accessing Off-by-One Errors

One of the most common errors is the “off-by-one” error, where a loop runs too many times or too few times when an invalid index n accessed. For example, if you loop from 0 to arr.length rather than 0 to arr.length – 1, it will try to access an out-of-bounds index:

For example:

Java

Output:  

Accessing Off-by-One Errors

5. Improper Array Copy or Manipulation

When data is copied from one array to another, if the destination array is not large enough to hold the data being copied from the source array, an ArrayIndexOutOfBoundsException can occur. This occurs when copying the elements from an arrays without checking the destination array’s size.

For example:

Java

Output:  

Improper array copy or manipulation

6. Using Variables without Validation

When the index for accessing an array is calculated, and obtained from the user input, or derived from an external source, there’s a risk of using an invalid index if the value is not properly checked. If the index is negative or greater than or equal to the array’s length, it will result in an ArrayIndexOutOfBoundsException.

For example:

Java

Output: 

 Using variables without validation:

Prevention of ArrayIndexOutOfBoundsException in Java

To prevent the ArrayIndexOutOfBoundsException, the following points should be kept in mind:

  • One must check the limit of an array prior to accessing its elements.
  • An array in Java begins with index 0 and ends with index length – 1, so accessing outside this range of elements will result in an ArrayIndexOutOfBoundsException.
  • An empty array does not contain any elements, so attempting to access an element from such an array would raise an exception.
  • When iterating over the elements of an array with loops, take care of the starting and ending conditions of the loop, so that they are always within the range of an array.
  • Write test cases for the conditions, such as accessing the first or last element of an array, or working with empty arrays. This can help identify the out-of-bounds errors

Best Practices to Avoid ArrayIndexOutOfBoundsException in Java

To find the Array Index Out Of Bounds Exception in a Java application, you can use a combination of the following methods:

  • Adding the try-catch blocks around the code can cause the exception. The catch block will contain a print statement to print the exception message and the stack trace.
  • Use a debugger in the code to check for the values of variables at each step. This can help you to find the specific line of code that is causing the exception and the values of the variables involved.
  • Turn on Logging into your application and check for the log files for any error messages or stack traces that are related to the ArrayIndexOutOfBoundsException.
  • Use an Application Performance Management (APM) Tool like FusionReactor which will check your application for errors. This can provide information about the error like the line number and method name.
Unlock Your Future in Java
Start Your Java Journey for Free Today
quiz-icon

How to Fix an ArrayIndexOutOfBoundsException in Java?

To fix an ArrayIndexOutOfBoundsException in Java, you need to ensure that you are always accessing array elements having valid index. The index of an array should be between 0 and array.length – 1, where array.length is the number of elements in the array. Here are some steps you can use to fix it:

1. Check the Index Before Accessing the Array

Always check that the index you’re using is within the range of the array. This ensures that you’re not trying to access an element that doesn’t exist.

2. Use Loops Carefully

When iterating through an array using a loop, ensure the loop runs within the valid range of indices. For example, a common mistake is using i <= arr.length in the loop condition, which causes the loop to go one iteration too many.

Incorrect Loop 

for (int i = 0; i <= arr.length; i++) {  //     i < =arr.length

    System.out.println(arr[i]);

}


Fixed Loop

for (int i = 0; i < arr.length; i++) {  // it should be i < arr.length

    System.out.println(arr[i]);

}

3. Handle Empty Arrays

An empty array has no elements, so any attempt to access an element will result in an ArrayIndexOutOfBoundsException. So always check if the array is empty before accessing elements.

4. Check Multi-Dimensional Array Indices

When working with multi-dimensional arrays (e.g., 2D arrays), ensure that both row and column indexes are within bounds. Each dimension in a multi-dimensional array has its own length.

5. Use Try-Catch Blocks for Exception Handling

Although preventing ArrayIndexOutOfBoundsException is ideal, you can also fix it using a try-catch block. The try-catch block catches the ArrayIndexOutOfBoundsException and prevents the program from crashing.  

Java

Output:

Use Try-Catch Blocks for Exception Handling

By following the above steps, you can fix an ArrayIndexOutOfBoundsException in Java applications.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

ArrayIndexOutOfBoundsException in Java occurs when an illegal index is used to access an element from an array. To prevent this, you should always check that the index stays in the range, i.e., between 0 and array.length – 1. The best practices include bounds checking before accessing, loop handling with care, and the use of exception handling i.e., try-catch blocks to avoid a crash of the application.

If you want to learn more about Java, you can refer to our Java Course.

Array Index Out Of Bounds Exception in Java – FAQs

Q1. What is ArrayIndexOutOfBoundsException in Java?

An ArrayIndexOutOfBoundsException is thrown when an index out of range is accessed. An out-of-range index occurs when the index is less than zero or greater than or equal to the size of the array.

Q2. How to prevent exceptions in Java?

You can use the normal try-catch syntax to prevent exceptions. In the catch block, you can mention the exception.

Q3. What causes null Java?

The java. lang. NullPointerException is a runtime exception thrown in Java when an application wants to use an object reference that has not been initialized 

Q4. How to prevent ArrayIndexOutOfBoundsException?

To prevent ArrayIndexOutOfBoundsException, always ensure that the index is within the range, i.e. from 0 to array.length – 1 before accessing array elements.

Q5. How is ArrayIndexOutOfBoundsException handled in Java?

To handle ArrayIndexOutOfBoundsException, make sure that the index of an array is within the valid range.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner