4

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?

2
  • You should never use such expressions. They're just confusing, error-prone and hard to debug. Commented Dec 27, 2011 at 15:15
  • 1
    They still exist and we must know everything associated with such stuff in Java or in any language. Commented Dec 27, 2011 at 15:22

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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

Comments

1
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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.