Reputation: 1189
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.
Upvotes: 0
Views: 127
Reputation: 129497
System.out.println( a [ (a = b)[3] ] );
First, the value of a
is evaluated ({1, 2, 3, 4}
). Next, a = b
is executed; this assigns the value of b
to a
and also returns the value of b
. b[3] = { 2, 3, 1, 0 }
is 0
, so, ultimately, {1,2,3,4}[b[3]] = {1,2,3,4}[0] = 1
.
To see this, consider the following:
public static void main(String[] args) throws FileNotFoundException {
int[] a = { 1, 2, 3, 4 };
System.out.println( a() [ (a = b())[c()] ] );
}
public static int[] a() {
System.out.println('a');
return new int[]{ 1, 2, 3, 4 };
}
public static int[] b() {
System.out.println('b');
return new int[]{ 2, 3, 1, 0 };
}
public static int c() {
System.out.println('c');
return 3;
}
Output:
a
b
c
1
Upvotes: 3
Reputation: 116100
At the moment you refer to a[ ... ]
, a
still points to the first array. When the index itself is evaluated, there's an assignment of b
to a
. So at that moment, a
becomes b
, of which the 3rd item is fetched, which is 0
.
This 0
is used as an index of the array that was already found before. This is the array that a
pointed to, although a
itself in the mean time has changed. Therefor it prints the 1
, even though you might expect 2
.
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.
Upvotes: 4