Why is x == (x = y) not the same as (x = y) == x?
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 values
x = 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 3
1 == 3
false
and to calculate the second:
(x = y) == x
(x = 3) == x //assign 3 to x, returns 3
3 == x
3 == 3
true
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.
==
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