Search code examples
javaoperator-precedence

In Java, why does an assignment in parentheses not occur before the rest of the expression is evaluated?


Consider

int a = 20;
a = a + (a = 5); // a == 25, why not 10?

Don't parentheses trump all precedence rules? Are some variables on the RHS prepopulated before evaluation of certain expressions?


Solution

  • Because a is loaded first in the example you have, and then the bit in parenthesis is evaluated. If you reversed the order:

    int a = 20;
    a = (a = 5) + a;
    System.out.println(a);
    
    10
    

    ... you do indeed get 10. Expressions are evaluated from left to right.

    Consider this:

    f() + g()
    

    f will be called before g. Imagine how unintuitive it would be, in

    f() + (g())
    

    to have g be called before f.

    This is all detailed in JLS §15.7.1 (thanks to @paisanco for bringing it up in the comments).