[英]Java Logical Operator And/Or Precedence
So everywhere I look, it says that && is evaluated first, then ||所以无论我看哪里,它都说 && 首先被评估,然后是 || is evaluated second.被评估第二。 So either I am doing something wrong or it is wrong.所以要么我做错了什么,要么是错误的。 Here's the code:这是代码:
static boolean foo(boolean b, int id){ System.out.println(id); return b;}
static{ System.out.println(foo(true, 3) && foo(true, 1) || foo(false, 2)) }
//returns 3 1
static{ System.out.println(foo(true, 2) || foo(true, 3) && foo(true, 1)}
//returns 2
In the first static block, && goes first, short circuits and ignores the ||在第一个静态块中,&& 先行,短路并忽略 || but in the second static block which is simply the reverse, ||但在第二个静态块中,正好相反, || goes first and ignored the &&.首先忽略&&。 This demonstrates left to right but according to the java doc, && has higher precedence which means && should always go first.这演示了从左到右,但根据 java doc,&& 具有更高的优先级,这意味着 && 应该总是先行。
Some documents about precedence (logical and is higher than or ):一些关于优先级的文档(逻辑和高于或):
1. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html 1. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
2. https://chortle.ccsu.edu/Java5/Notes/chap40/ch40_16.html 2. https://chortle.ccsu.edu/Java5/Notes/chap40/ch40_16.html
3. http://www.cs.bilkent.edu.tr/~guvenir/courses/CS101/op_precedence.html 3. http://www.cs.bilkent.edu.tr/~guvenir/courses/CS101/op_precedence.html
... ...
Higher predecence of &&
just means that &&
更高优先级仅意味着
foo(true, 2) || foo(true, 3) && foo(true, 1)
is the same as是相同的
foo(true, 2) || (foo(true, 3) && foo(true, 1))
but not但不是
(foo(true, 2) || foo(true, 3)) && foo(true, 1)
Nothing else.没有其他的。 It doesn't imply anything about evaluation order.它并不暗示任何有关评估顺序的内容。
Now, for most operators, evaluating x op y
requires evaluating both x
and y
.现在,对于大多数运算符,评估x op y
需要评估x
和y
。 If ||
如果||
was one of them, it would be the same as ( return
is from evaluating ||
, not from the entire method)是其中之一,它将与( return
来自评估||
,而不是来自整个方法)相同
boolean tmp1 = foo(true, 2);
boolean tmp2 = foo(true, 3) && foo(true, 1);
return tmp1 || tmp2;
and &&
would indeed "go first".和&&
确实会“先行”。 But there are three operators which don't work like that: &&
, ||
但是有三个运算符不能这样工作: &&
, ||
and ?:
.和?:
。 Instead you get相反,你得到
boolean tmp1 = foo(true, 2);
if (tmp1) {
return true;
} else {
return foo(true, 3) && foo(true, 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.