In one example from http://leepoint.net/notes-java/data/expressions/precedence.html
Next expression
1 + 2 - 3 * 4 / 5
Calculated as
1 + 2 - 3 * 4 / 5
= (1 + 2) - ((3 * 4) / 5)
= 3 - (12/5)
= 3 - 2 The result of the integer division, 12/5, is 2 .
= 1
Then I saw another example from http://www.roseindia.net/java/master-java/operator-precedence.shtml
Next expression
4 + 5 * 6 / 3
estimated as
4 + (5 * (6 / 3))
I'm a little confused as to how the decision will be made, which will be evaluated first when * and / are involved. In the above examples, both seem to be the difference.
The first example evaluates 3*5/5to ((3*4)/5)
While the second example evaluates5*6/3 as (5*(6/3))
I know that * and / take precedence over + and - but what about when an expression includes both * and /. And also why the above examples demonstrate different approaches? Is one of them wrong?
Edit
public class ZiggyTest {
public static void main(String[] args) {
System.out.println(4 + (5 * (6 / 3)));
System.out.println(4 + ((5 * 6) / 3));
System.out.println(1 + 2 - (3 * (4 / 5)));
System.out.println(1 + 2 - ((3 * 4) / 5));
}
}
14
14
3
1
, .