This is the snippet of Java code.
class Test{
public static void main(String[ ] args){
int[] a = { 1, 2, 3, 4 };
int[] b = { 2, 3, 1, 0 };
System.out.println( a [ (a = b)[3] ] );
}
}
Why does it print 1? This is not a homework! I am trying to understand Java. That is related to OCA Java 7 exam.
At the moment you refer to
a[ ... ],astill points to the first array. When the index itself is evaluated, there’s an assignment ofbtoa. So at that moment,abecomesb, of which the 3rd item is fetched, which is0.This
0is used as an index of the array that was already found before. This is the array thatapointed to, althoughaitself in the mean time has changed. Therefor it prints the1, even though you might expect2.I think that is what this example is trying to show: The array reference is already evaluated and doesn’t change once you modify the array variable during the evaluation of the index.
But I wouldn’t use this ‘feature’ in production code. Very unclear.