Assigning values ​​to an array index

Please view the code snippet below and let me know how 1 2 comes out.

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

+6
source share
3 answers

I will try to explain:

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

  • a [...] - the array a will be read and the link will be saved for this
  • (a = b) - the variable a set to the reference array b
  • (a=b)[3] - the 4th element of the array b is read (due to step 2) the value 0
  • a [ (a = b)[3] ] - now this is equal to a[0] (due to steps 1 and 3) value 1

a[0] now gives 2 , since a refers to the array b (because of step 2), and the first element in this array is 2 .

+6
source
Seriously, what is the purpose of this? Why would you ever want to do something that makes the code so unreadable. What do you expect from the result?

Result System.out.println( a [ (a = b)[3] ] ); linked to the order in which things are put on the evaluation stack.

  • link to
  • change the link stored in character a stored in b
  • evaluated b [3] => 0
  • print index 0 of the array to which the link was clicked at 1.), that is, the original a

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

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

+7
source

The first two lines initialize your arrays. First sysout assigns b then a then prints [3], i.e. yours and now has values ​​{2,3,1,0}. The second sysout prints a [0].

0
source

Source: https://habr.com/ru/post/911390/


All Articles