It looks like the index
expression is evaluated first.
This test program confirms it:
public class Main {
public static void main(String[] args) {
int[] array = new int[10];
array[getIndex()] = getValue();
}
private static int getIndex() {
System.out.println("getIndex!");
return 0;
}
private static int getValue() {
System.out.println("getValue!");
return 1;
}
}
Output:
getIndex!
getValue!
The value is evaluated even if an ArrayIndexOutOfBoundsException
is thrown. Changing getIndex()
:
private static int getIndex() {
System.out.println("getIndex!");
return -1; // Hey!
}
Output:
getIndex!
getValue!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Main.main(Main.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:90)