Why is x == (x = y) not the same as (x = y) == x? Why is x == (x = y) not the same as (x = y) == x? java java

Why is x == (x = y) not the same as (x = y) == x?


== is a binary equality operator.

The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

Java 11 Specification > Evaluation Order > Evaluate Left-Hand Operand First


As LouisWasserman said, the expression is evaluated left to right. And java doesn't care what "evaluate" actually does, it only cares about generating a (non volatile, final) value to work with.

//the example valuesx = 1;y = 3;

So to calculate the first output of System.out.println(), the following is done:

x == (x = y)1 == (x = y)1 == (x = 3) //assign 3 to x, returns 31 == 3false

and to calculate the second:

(x = y) == x(x = 3) == x //assign 3 to x, returns 33 == x3 == 3true

Note that the second value will always evaluate to true, regardless of the initial values of x and y, because you are effectively comparing the assignment of a value to the variable it is assigned to, and a = b and b will, evaluated in that order, always be the same by definition.


which, by the order implied by brackets, should be calculated first

No. It is a common misconception that parentheses have any (general) effect on calculation or evaluation order. They only coerce the parts of your expression into a particular tree, binding the right operands to the right operations for the job.

(And, if you don't use them, this information comes from the "precedence" and associativity of the operators, something that's a result of how the language's syntax tree is defined. In fact, this is still exactly how it works when you use parentheses, but we simplify and say that we're not relying on any precedence rules then.)

Once that's done (i.e. once your code has been parsed into a program) those operands still need to be evaluated, and there are separate rules about how that is done: said rules (as Andrew has shown us) state that the LHS of each operation is evaluated first in Java.

Note that this is not the case in all languages; for example, in C++, unless you're using a short-circuiting operator like && or ||, the evaluation order of operands is generally unspecified and you shouldn't rely on it either way.

Teachers need to stop explaining operator precedence using misleading phrases like "this makes the addition happen first". Given an expression x * y + z the proper explanation would be "operator precedence makes the addition happen between x * y and z, rather than between y and z", with no mention of any "order".