Array Expressions in Java

Consider the following expressions in Java.

int[] x={1, 2, 3, 4}; int[] y={5, 6, 7, 0}; x=y; System.out.println(x[0]); 

5 appears 5 the console because x will point to y through the expression x=y and x[0] , obviously it will be evaluated as 5 , which is actually the value of y[0] .

When I replace the above two operators with the following statement, combining both of them into one operator,

 System.out.println(x[(x=y)[3]]); 

it displays 1 , which is the value of x[0] , even if it seems to be equivalent to the one above of the two operators. How?

+4
source share
5 answers

the third index in the y array points to 0, so 1 is the correct output.

So you have

x[(x=y)[3]]

which is x[y[3]] , but y[3] is 0, because arrays are indexed 0, and x[0] is 1.

+6
source

This is because x = y creates a new x inside the index. So now x[3] = y[3] = 0 and x[0] = 1 , because it still uses the old array x outside.

+2
source

The Java programming language ensures that operands of operators will be evaluated in a specific evaluation order, namely, from left to right.

 ...println(x[y[3]]); // 1 
+1
source
 x[(x=y)[3]] 

breaks down into

 int[] z = y; // new "temp" array (x=y) in your expression above int i = z[3]; // index 3 in y is 0 System.out.println(x[i]); // prints x[0] based on the value of i...which is 1 
+1
source

All about priority here.

let's look at it

we have the following expression

x = 2 + 5 * 10

therefore, by starting the expression about, it is first multiplied by 5 * 10, then added to 2 and assigned x, since the priority "=" is the smallest

x [(x = y) [3]] in this case, what is most confusing is the fact that the term (x = y), and most programmers believe that it first assigns the link y to x, and then goes to the rest, but here assignment operator solved minimum

that is why when you try to output x [0] after running the above expression, then I will give the value 5, because the zero index y contains 5

0
source

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


All Articles