java.lang.ArrayIndexOutOfBoundsExcepiton in Java with Examples


java.lang.ArrayIndexOutOfBoundsException is a runtime exception that occurs when an attempt is made to access an array element with an index that is either negative or greater than or equal to the length of the array. This exception is thrown by the Java Virtual Machine (JVM) when it detects an illegal array index.

Here are some examples of how this exception can occur:

Example 1: Accessing an array element with an index that is out of bounds

int[] arr = {1, 2, 3};
System.out.println(arr[3]); // throws ArrayIndexOutOfBoundsException

In this example, the array arr has a length of 3, which means its valid indices are 0, 1, and 2. However, we are trying to access the element at index 3, which is out of bounds and will result in an ArrayIndexOutOfBoundsException.

Example 2: Using a negative index to access an array element

int[] arr = {1, 2, 3};
System.out.println(arr[-1]); // throws ArrayIndexOutOfBoundsException

In this example, we are trying to access the element at index -1, which is not a valid index for the array arr. This will result in an ArrayIndexOutOfBoundsException.

Example 3: Using a variable as an array index without checking its value

int[] arr = {1, 2, 3};
int index = 4;
System.out.println(arr[index]); // throws ArrayIndexOutOfBoundsException

In this example, we are using the variable index as an array index without checking its value. The value of index is 4, which is out of bounds for the array arr. This will result in an ArrayIndexOutOfBoundsException.

To avoid this exception, you should always make sure that the index you are using to access an array element is within the bounds of the array. Here are some ways to do this:

  • Use a loop to iterate over the array and check the index before accessing the element:
int[] arr = {1, 2, 3};
for (int i = 0; i < arr.length; i++) {
    if (i == 3) {
        // do something with arr[i]
    }
}
  • Use the Arrays class to check the index before accessing the element:
int[] arr = {1, 2, 3};
int index = 3;
if (index >= 0 && index < arr.length) {
    // do something with arr[index]
} else {
    // handle the out of bounds case
}
  • Use an if statement to check the index before accessing the element:
int[] arr = {1, 2, 3};
int index = 3;
if (index >= 0 && index < arr.length) {
    // do something with arr[index]
} else {
    // handle the out of bounds case
}


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.