Operator precedence in Java

后端 未结 3 1922
轮回少年
轮回少年 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).

提交回复
热议问题