Java primitive variable reassignment during expression

171 Views Asked by At

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);
    }
}
2

There are 2 best solutions below

4
On BEST ANSWER
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.

4
On

In Java when assigning a value to a variable, the first thing that is calculated is the left part of the = sign and then the right. Therefore, when you write a += (a = 4); which is equivalant to a = a + (a=4) which is the same as a = a + 4 , same for b.