Why not throwing an ArrayIndexOutOfBoundsException?
Let's take a look at the following code:
public Class Program{
public static void main(String[] args){
int i = 0;
int[] a = {1,2};
a[i] = i = 2;
System.out.println(i + " " + a[0]+ " "+a[1]);
}
}
What is the output from the above code?
The output is:
2 2 2
You may raise some questions: "When does i get a value 2?", "Why doesn't it use the same value (i=2) for a[i] (which should actually give an ArrayOutOfBoundsException Exception)?", and so on.
The reason no ArrayIndexOutOfBoundsException is thrown is because each of the operands is evaluated from left to right. Basically the array reference is evaluated first then the rest of the expression is done according to the rules in the posted on 2010-07-08 14:25 gembin 閱讀(430) 評論(0) 編輯 收藏 所屬分類: JavaSE