title: Why is x == (x = y) not the same as (x = y) == x?
body: <p>Consider the following example:</p>
  
  <pre><code>class Quirky {
      public static void main(String[] args) {
          int x = 1;
          int y = 3;
  
          System.out.println(x == (x = y)); // false
          x = 1; // reset
          System.out.println((x = y) == x); // true
       }
  }
  </code></pre>
  
  <p>I'm not sure if there is an item in the Java Language Specification that dictates loading the previous value of a variable for comparison with the right side (<code>x = y</code>) which, by the order implied by brackets, should be calculated first.</p>
  
  <p>Why does the first expression evaluate to <code>false</code>, but the second evaluate to <code>true</code>? I would have expected <code>(x = y)</code> to be evaluated first, and then it would compare <code>x</code> with itself (<code>3</code>) and return <code>true</code>.</p>
  
  <hr>
  
  <p>This question is different from <a href="https://stackoverflow.com/questions/32755655/order-of-evaluation-of-subexpressions-in-a-java-expression">order of evaluation of subexpressions in a Java expression</a> in that <code>x</code> is definitely not a 'subexpression' here. It needs to be <strong>loaded</strong> for the comparison rather than to be 'evaluated'. The question is Java-specific and the expression <code>x == (x = y)</code>, unlike far-fetched impractical constructs commonly crafted for tricky interview questions, came from a real project. It was supposed to be a one-line replacement for the compare-and-replace idiom</p>
  
  <pre><code>int oldX = x;
  x = y;
  return oldX == y;
  </code></pre>
  
  <p>which, being even simpler than x86 CMPXCHG instruction, deserved a shorter expression in Java.</p>