Reputation: 19027
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]);
Would display 5
on the console because x
is made to point to y
through the expression x=y
and x[0]
would obviously be evaluated to 5
which is actually the value of y[0]
.
When I replace the above two statements with the following statement combining both of them into a single statement,
System.out.println(x[(x=y)[3]]);
it displays 1
which is the value of x[0]
even though it seems to be equivalent to those above two statements. How?
Upvotes: 4
Views: 2328
Reputation: 188
It's all about the precedence here
lets take a look at this
we have following expression
x= 2 + 5 *10
so on running the about expression it first multiply 5 * 10 then add it with 2 and assign it to the x because the precedence of "=" is least
x[(x=y)[3]] in this case what confuses the most is that (x = y ) term, and most of programmers think that it assigns the reference of y to x first then proceed with the remaining part but here assignment operator is resolved least
that's why when you try to print the x[0] after the above expression is run, then i will give value of 5 because the zeroth index of y contains 5
Upvotes: 0
Reputation: 36573
x[(x=y)[3]]
breaks down to
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
Upvotes: 1
Reputation: 82614
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
...println(x[y[3]]); // 1
Upvotes: 1
Reputation: 62439
It's because x = y
produces the new x inside the index. So now x[3] = y[3] = 0
and x[0] = 1
, because it still uses the old x
array on the outside.
Upvotes: 2
Reputation: 120198
the third index in the array y points to is 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 0-indexed, and x[0]
is 1.
Upvotes: 6