Reallocating a primitive array with different size gives ArrayIndexOutOfBoundException

Viewed 34
    static int[] array = new int[1];

    static int fun() {
        array = new int[10];
        return 3;
    }

    public static void main(String[] args) {
        array[fun()] = 2;
    }

Why does the above code give ArrayIndexOutOfBoundsException while:

    public static void main(String[] args) {
    fun();  
    array[3] = 2;
    }

does not!

Thanks.

1 Answers

It's due to the way array access is evaluated at runtime, as described in Section 15.10.4 from the Java Language Specification:

At run time, evaluation of an array access expression behaves as follows:

  • First, the array reference expression is evaluated. If this evaluation completes abruptly, then the array access completes abruptly for the same reason and the index expression is not evaluated.
  • Otherwise, the index expression is evaluated. If this evaluation completes abruptly, then the array access completes abruptly for the same reason.
  • Otherwise, if the value of the array reference expression is null, then a NullPointerException is thrown.
  • Otherwise, the value of the array reference expression indeed refers to an array. If the value of the index expression is less than zero, or greater than or equal to the array's length, then an ArrayIndexOutOfBoundsException is thrown.

Note that the array reference expression is evaluated before the index expression is evaluated. By the time the index expression is called, the array to be evaluated against has been already evaluated. Needless to say, changing the array within the index expression is asking for trouble.

Related