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
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]
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With