All Products
Search
Document Center

java_lang_ArrayIndexOutOfBoundsException

Last Updated: Feb 28, 2022

Problem description

The array index exceeds the specified threshold and the size of the referenced object surpasses that of the array.

Solution

The array index exceeds the specified threshold and the size of the referenced object surpasses that of the array. Check the array size before you manage the array to determine whether the referenced object exists. If yes, the object is returned. Otherwise, null is returned.

Sample code

public String arrayOutOfBounds(String[] array, int index){
    if(array!=null && array.length>index && index>=0){
        System.out.println("content is: "+array[index]);
        return array[index];
    }
    return null;
}

Example:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at com.alibaba.mqc.test.Test.arrayOutOfBounds(Test.java:52)
at com.alibaba.mqc.test.Test.main(Test.java:31)

This crash occurs because the array is 0 in size but the object of the array is obtained. The root cause is that the array index exceeds the specified threshold when the Get operation is invoked on the array as specified in line 86 of the SourceFile.

References