Java中的运算符优先级 [英] Operator precedence in Java

查看:272
本文介绍了Java中的运算符优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://leepoint.net/notes-java/data/expressions/precedence.html

以下表达式

1 + 2 - 3 * 4 / 5

被评估为

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

然后,我从 http://www.roseindia中看到了另一个示例. net/java/master-java/operator-precedence.shtml

以下表达式

4 + 5 * 6 / 3

评估为

4 + (5 * (6 / 3))

当涉及到*和/时,对于如何首先确定哪个值,我有些困惑.在上面的示例中,两者似乎有所不同.

I am slightly confused as to how it is decided which will be evaluated first when * and / are involved. In the examples above, both seem to be difference.

第一个示例将3*5/5评估为((3*4)/5) 而第二个示例正在评估5*6/3 as (5*(6/3))

The first example is evaluating 3*5/5 as ((3*4)/5) Whereas the second example is evaluating 5*6/3 as (5*(6/3))

我知道*和/优先于+和-,但是当表达式同时包含*和/时该怎么办.还有,为什么上述两个示例显示了不同的方法?其中之一是错的吗?

I know that * and / have precedence over + and - but what about when the expression includes both * and /. And also why are the above two examples showing different approaches? Is one of them wrong?

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

如果前两个输出相同,为什么最后两个输出不相同.

Why are the last two outputs not the same if the first produced the same output.

推荐答案

我对如何确定在涉及*和/时将首先进行评估感到困惑

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 :)

第15.7节是Java语言规范的一部分,处理评估顺序,并且第15.17节指出:

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).

因此,只要存在A op1 B op2 C,并且op1op2均为*/%,它等效于

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));

输出:

-357913942
-357913942
1073741823

这表明发生在 first 的乘法(导致整数溢出),而不是除法(以1的乘法运算结束).

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

这篇关于Java中的运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆