Reputation: 8664
Please look at the below code snippet and let me know how the out comes out as 1 2 .
int[] a = { 1, 2, 3, 4 };
int[] b = { 2, 3, 1, 0 };
System.out.println( a [ (a = b)[3] ] );
System.out.println(a[0]);
Actual answer 1 2
Thanks
Upvotes: 6
Views: 1852
Reputation: 2262
First two lines initialize your arrays. First sysout assigns b to a then prints a[3], ie. your a is now having values {2,3,1,0}. Second sysout prints a[0].
Upvotes: 0
Reputation: 88707
I'll try to explain:
a [ (a = b)[3] ]
will be executed in the following order:
a [...]
- the array a
will be read and the reference is stored for that(a = b)
- the variable a
is set to reference array b
(a=b)[3]
- the 4th element of array b
is read (because of step 2) , the value is 0
a [ (a = b)[3] ]
- this is now equal to a[0]
(because of steps 1 and 3), the value is 1
a[0]
now yields 2
since a
references array b
(because of step 2) and the first element in that array is 2
.
Upvotes: 6
Reputation: 13755
Seriously, what is the purpose of this? Why would you ever wanna do something that makes the code so unreadable. What would you expect the outcome to be?
The result of System.out.println( a [ (a = b)[3] ] );
has to do with the order in which things are pushed to the evaluation stack ... e.g.
so it prints the element at 0 of the original a
array
System.out.println(a[0]);
is then simply b[0]
Upvotes: 7