Java运算符优先 [英] Java operators precedence

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

问题描述

由于Java中运算符优先级的原因,我感到很困惑。我很久以前在教程中读到AND的优先级高于OR,这可以通过问题。但是,我目前正在使用Sun认证的Java 6程序员学习指南来学习Java。本书包含以下示例:

I have got confused due to what is true regarding the operator precedence in Java. I read in tutorials a long time ago that AND has a higher priority than OR, which is confirmed by the answers provided in the question. However, I am currently studying Java using the "Sun Certified Programmer for Java 6 Study Guide". This book contains the following example:

int y = 5;
int x = 2;
if ((x > 3) && (y < 2) | doStuff()) {
    System.out.println("true");
}

我正在复制并引用编译器如何处理上述代码的说明:

I am copying and citing the explanation of how the compiler handles the above code:


如果(x> 3) true ,以及(y <2)
doStuff() true ,然后打印true。由于
短路&&& ,表达式的评估就好像在$ code>周围有
括号一样(y < 2)| doStuff()
。换句话说,它是
&&& 之前的单个表达式和之后的单个
表达式。 &&&

If (x > 3) is true, and either (y < 2) or the result of doStuff() is true, then print "true". Because of the short-circuit &&, the expression is evaluated as though there were parentheses around (y < 2) | doStuff(). In other words, it is evaluated as a single expression before the && and a single expression after the &&.

这意味着虽然 | 的优先级高于&& 。是由于使用非短路OR而不是短路OR?什么是真的?

This implies though that | has higher precedence than &&. Is it that due to the use of the "non-short-circuit OR" and instead of the short circuit OR? What is true?

推荐答案

那是因为它使用 | 运算符而不是 || ,具有更高的优先级。 这是表格。

That's because it is using the | operator instead of ||, which has a higher priority. Here's the table.

使用 || 运算符,它会按照您的想法行事。

Use the || operator instead and it'll do what you think.

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

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