Operator Priority in Java

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

, .

+5
3

, , , * /

:)

15.7 - Java, , 15.17 :

*,/% . - ( ).

, A op1 B op2 C, op1 op2 *, / %,

(A op1 B) op2 C

, , . , :

int x = Integer.MAX_VALUE / 2;        
System.out.println(x * 3 / 3);
System.out.println((x * 3) / 3);
System.out.println(x * (3 / 3));

:

-357913942
-357913942
1073741823

, ( ), ( 1).

+11

?

4 + (5 * 6) / 3
4 + 30 / 3
4 + 10
14

4 + 5 * (6 / 3)
4 + 5 * 2
4 + 10
14

, . . , , .

+3

. . . . :

4 + 5 * 6 / 3

4 + ((5 * 6) / 3).

In this case, however, the wrong grouping

4 + (5 * (6 / 3))

gives the same answer.

+2
source

All Articles