In what order does Java add up the numbers a + b + c?
Is it a + (b + c) or (a + b) + c?
I just learned how floating point representation works and finished an exercise which explained that if a, b, c are floats, they might yield a different result when added up in the different ways I wrote above.
That left me wondering which way Java actually does it?
The addition operator is left associative, meaning that a + b + c is evaluated the same as (a + b) + c.
The JLS, Section 15.18, states:
The additive operators have the same precedence and are syntactically left-associative (they group left-to-right).
Left to right (jls-15.18) unless you add parenthesis to alter 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 is
a
b
2
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