Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of addition in Java

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?

like image 753
J0hj0h Avatar asked Feb 10 '26 14:02

J0hj0h


2 Answers

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

like image 86
rgettman Avatar answered Feb 13 '26 10:02

rgettman


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
like image 34
Elliott Frisch Avatar answered Feb 13 '26 09:02

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!