Operator precedence in Java

后端 未结 3 1923
轮回少年
轮回少年 2020-12-17 02:01

In one example from http://leepoint.net/notes-java/data/expressions/precedence.html

The following expression

1 + 2 - 3 * 4 / 5

Is

相关标签:
3条回答
  • 2020-12-17 02:26

    I am slightly confused as to how it is decided which will be evaluated first when * and / are involved

    That's why we have specifications :)

    Section 15.7 is the section of the Java Language Specification which deals with evaluation order, and section 15.17 states:

    The operators *, /, and % are called the multiplicative operators. They have the same precedence and are syntactically left-associative (they group left-to-right).

    So whenever there is A op1 B op2 C and both op1 and op2 are *, / or % it's equivalent to

    (A op1 B) op2 C
    

    Or to put it another way - the second linked article is plain wrong in their example. Here's an example to prove it:

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

    Output:

    -357913942
    -357913942
    1073741823
    

    That shows the multiplication happening first (leading to integer overflow) rather than the division (which would end up with a multiplication of 1).

    0 讨论(0)
  • 2020-12-17 02:28

    Are you sure?

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

    They produce the same output because adding the parentheses don't happen to change the result. For your other equation, the parentheses actually do change the result. By removing the parentheses in the equations I solved, the correct path to the result is the first one.

    0 讨论(0)
  • 2020-12-17 02:46

    The second one is wrong. See Jon Skeet's answer. Multiplicative operators evaluate left to right. The grouping for:

    4 + 5 * 6 / 3
    

    should be

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

    In this case, though, the wrong grouping

    4 + (5 * (6 / 3))
    

    yields the same answer.

    0 讨论(0)
提交回复
热议问题