Consider the following example:
class Quirky {
public static void main(String[] args) {
int x = 1;
int y = 3;
System.out.println(x =
It is related to operator precedence and how operators are getting evaluated.
Parentheses '()' has higher precedence and has associativity left to right. Equality '==' come next in this question and has associativity left to right. Assignment '=' come last and has associativity right to left.
System use stack to evaluate expression. Expression gets evaluated left to right.
Now comes to original question:
int x = 1;
int y = 3;
System.out.println(x == (x = y)); // false
First x(1) will be pushed to stack. then inner (x = y) will be evaluated and pushed to stack with value x(3). Now x(1) will be compared against x(3) so result is false.
x = 1; // reset
System.out.println((x = y) == x); // true
Here, (x = y) will be evaluated, now x value become 3 and x(3) will be pushed to stack. Now x(3) with changed value after equality will be pushed to stack. Now expression will be evaluated and both will be same so result is true.