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?

+3


source to share


3 answers


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

+8


source


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

      

+3


source


Order a + b + c

is equal to order (a + b) + c

(left associativity).

+2


source







All Articles