Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 302
jordanpg Avatar asked Dec 20 '22 12:12

jordanpg


2 Answers

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).

like image 131
arshajii Avatar answered Jan 26 '23 00:01

arshajii


From the JLS

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

and

The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

Wrapping an expression in parentheses just helps grouping (and associativity), it doesn't force its evaluation to happen before anything to its left.

like image 43
Sotirios Delimanolis Avatar answered Jan 25 '23 23:01

Sotirios Delimanolis