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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With