Search code examples
javainteger-arithmeticjava-17

Assigning a variable during arithmetic in Java?


My professor gave us this java snippet during a lecture and I don't understand why it outputs 12.

int b = 9; 
b = b + (b = 3); 
System.out.println( "b = " + b );

My thinking is that since parentheses give operations precedence, b would be reassigned to 3 first. Then, it would go b = 3 + 3 = 6. Obviously, this isn't the case and b = 9 + 3 = 12 is actually executed. Why is the code executed left to right and not parentheses first?

Excuse my poor title, I'm not sure what to call this because I don't think you ever actually program this way.


Solution

  • Precedence does not mean that it runs first. It merely lets you rewire operator precedence. Ordinarily something like 1 + 2 * 3 is resolved as:

    • A plus operation between A and B, where
    • A is the integer literal '1'
    • B is the expression 2 * 3.

    Why? Because operator precedence rules state that * binds tighter than +. With parens you can override that; (1 + 2) * 3 is a multiply operation between A and B where B is a '3' literal and A is '1 + 2'. That's all it does. It doesn't change the order in which things are resolved.

    Java first evaluates 'b' (it's 9), then it evaluates (b = 3) (which is 3, and as a side effect, makes b become 3), and thus that expression is 12, which is then assigned to b, so it's 12.

    Why does it evaluate the left hand side of that + first? Because the spec says so: resolves left to right.

    Try this for funsies:

    int b = 9;
    b = (b = 3) + b;
    System.out.println(b);
    

    now it prints 6 as expected.