Java运算符优先 [英] Java operators precedence
问题描述
由于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()$ c的结果$ c>是
。换句话说,它是true
,然后打印true
。由于
短路&&&
,表达式的评估就好像在$ code>周围有
括号一样(y < 2)| doStuff()
在&&&
之前的单个表达式和之后的单个
。
表达式。 &&&
If (x > 3)
istrue
, and either(y < 2)
or the result ofdoStuff()
istrue
, 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屋!