Java add order
In what order a + b + c
does Java add numbers ?
Is it a + (b + c)
or (a + b) + c
?
I just learned how floating point representation works, and ended up with an exercise that explains that if s a, b, c
are float
, they can give a different result when added in the various ways described above.
This got me thinking, how does Java actually do it?
source to share
The append operator remains associative, which means it a + b + c
evaluates the same as (a + b) + c
.
JLS, section 15.18 , says:
Additive operators have the same precedence and are syntactically left-associative (they are grouped from left to right).
source to share
Left to right (jls-15.18) unless you add parentheses to change the order of evaluation.
static int a() {
System.out.println("a");
return 1;
}
static int b() {
System.out.println("b");
return 1;
}
public static void main(String[] args) {
System.out.println(a() + b());
}
Output
a
b
2
source to share