Search code examples
javavariable-assignmentexpression-evaluation

Java primitive variable reassignment during expression


I had a question in my test that I got confused about (code attached below). To put it shortly, I thought that the variables are reassigned and then added back as a value to the expression (making the output "8, 10") but seems like the original value somehow is not changed. What am I missing?

p.s. Sorry if a similar question exists, I couldn't find one (probably its too obvious :P).

class InitTest{
    public static void main(String[] args){
        int a = 10;
        int b = 20;
        a += (a = 4);
        b = b + (b = 5);
        System.out.println(a + ",  " + b);
    }
}

Solution

  • a += (a = 4);
    

    The above is logically equivalent to the following:

    a = a + (a = 4);
    

    If we substitute in the existing value for a, then this simplifies to:

    a = 10 + 4 = 14
    

    We can do the same for b:

    b = b + (b = 5) = 20 + 5 = 25
    

    We see this result because of operator precedence. The addition operator, +, has a higher precedence than the assignment operator, =, as defined by the Java operator precedence table.

    You can see that the addition-assignment operator, +=, shares the same precedence with the assignment operator, in which case the expression is evaluated from left to right.


    If, instead, the expressions were:

    a = (a = 4) + a;
    b = (b = 5) + b;
    

    Then it would result in the output that you expect (a = 8, b = 10), as the left operand is computed before the right operand (when evaluating the expression). I'll try to locate where this is specified in the Java Language Specification.