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);
}
}
The above is logically equivalent to the following:
If we substitute in the existing value for
a, then this simplifies to:We can do the same for
b: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:
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.