Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment of values in a array index

Tags:

java

arrays

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

like image 503
Sudarshan Avatar asked Mar 22 '12 09:03

Sudarshan


2 Answers

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.

  1. reference to a
  2. change reference stored in a to that stored in b
  3. evaluated b[3] => 0
  4. print index 0 of the array to which reference was pushed in 1.), i.e. the original a

so it prints the element at 0 of the original a array

System.out.println(a[0]); is then simply b[0]

like image 109
scibuff Avatar answered Sep 22 '22 01:09

scibuff


I'll try to explain:

a [ (a = b)[3] ] will be executed in the following order:

  1. a [...] - the array a will be read and the reference is stored for that
  2. (a = b) - the variable a is set to reference array b
  3. (a=b)[3] - the 4th element of array b is read (because of step 2) , the value is 0
  4. 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.

like image 41
Thomas Avatar answered Sep 21 '22 01:09

Thomas