Assigning a variable value in a chain in Java

Possible duplicate:
Java - order of operations - using two assignment operators on a separate line

If we assign a variable a value in the chain as shown below,

int x=10, y=15; int z=x=y; System.out.println(x+" : "+y+" : "+z); 

then the value of all three variables x , y and z will become 15 .


However, I do not understand the following phenomenon with an array.

 int array[]={10, 20, 30, 40, 50}; int i = 4; array[i] = i = 0; System.out.println(array[0]+" : "+array[1]+" : "+array[2]+" : "+array[3]+" : "+array[4]); 

It displays 10 : 20 : 30 : 40 : 0 . It replaces the value of the last element of array[4] with 0 .

As for the previous assignment operator - int z=x=y; , I expect that the value of the first element means array[0] to replace with 0 . Why is this not so? It is simple, but I cannot understand. Could you explain?


By the way, this assignment operator array[i] = i = 0; is fictitious and it has no intrinsic value in this code and should no longer be used, but I just wanted to know how it actually works in this case.

+4
source share
4 answers

int i = 4; when I equal 4, the value of array[i] is equal to array[4] , so array[i] = i = 0; equivalent to array[4] = i = 0; . So this is a change in the value of index 4 from 0.

+6
source

The separators [] and () change the priority. Everything inside these delimiters will be computed before Java looks outside of them.

 array[i] = i = 0; 

During compiler phases, the first change to this line will occur as follows:

 array[4] = i = 0; // subscript separator is evaluated first. 

Now the assignment operation is right-associative, therefore i assigned the value 0 , and then the array [4] is assigned the value i ie 0 .

Check out the following links:

+4
source

Let me break it ....

Your statement:

int array[]={10, 20, 30, 40, 50};

Implementation:

 array[0] => 10 array[1] => 20 array[2] => 30 array[3] => 40 array[4] => 50 

Your statement:

int i = 4;

Implementation:

 i => 4 

Your statement:

array[i] = i = 0;

Implementation:

 array[4] = i = 0; array[4] = 0 

Well, if you want array[0] => 0 , then do it ...

 int i = 0; array[i] = i = 0 
+3
source

because array[i] is evaluated before opeartion assignment

+2
source

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


All Articles