Sudarshan
Sudarshan

Reputation: 8664

Assignment of values in a array index

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

Answers (3)

sgowd
sgowd

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

Thomas
Thomas

Reputation: 88707

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.

Upvotes: 6

scibuff
scibuff

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.

  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]

Upvotes: 7

Related Questions