While studying Java I came across the expression 4 + 20 / (3 - 1) * 2
.
In Eclipse, this expression is evaluated to 24.
So, it could be interpreted as 4 + ((20 / (3 - 1)) * 2)
.
Why is it wrong to interpret 4 + 20 / (3 - 1) * 2 as 4 + (20) / ((3 - 1) * 2)
which would result to 9?
Thanks a lot for your help.
UPDATE
To be more specific in my question, mathematically, unless misunderstanding or misinterpretation on my part, 4 + 20 / (3 - 1) * 2 is ambiguous as I learn from this paper https://math.berkeley.edu/~gbergman/misc/numbers/ord_ops.html by George Bergman, a professor at the University of California, Berkeley. One can interpret it as 4 + ((20 / (3 - 1)) * 2)
or 4 + (20) / ((3 - 1) * 2)
.
However, in Java, the 4 + ((20 / (3 - 1)) * 2)
interpretation appears to be right while the 4 + (20) / ((3 - 1) * 2)
interpretation appears to be wrong. In both interpretations, things in parentheses get computed first, then multiplication and division are performed and finally addition and subtraction are performed. The only difference that i see between the two is that in the right interpretation division is done first while in the wrong interpretation multiplication is done first.
My question is then in Java what is the key factor that makes one interpretation right and the other wrong.
Thanks!
Order of operations states that the inner most parentheses are evaluated first then multiplication and division from left to right then addition and subtraction left to right. The left to right principle is important here. This order of operations is standard in mathematics and Java (as well as most languages) follow the standard for mathematics. Order of Operations