[英]Java order of expression evaluation with AND and OR
boolean a = false;
boolean b = false;
boolean c = false;
boolean bool = (a = true) || (b = true) && (c = true);
System.out.println("" + a + b + c);
The prceding code prints truefalsefalse
. 上面的代码显示
truefalsefalse
。 But, the &&
operator has higher precedence than the ||
但是,
&&
运算符的优先级高于||
operator and should be evaluated first, so why doesn't it print truetruetrue
? 运算符,并且应该首先对其进行评估,所以为什么不输出
truetruetrue
呢?
I believe the crux of your question is this part: 我相信您的问题的关键是这部分:
But, the && operator has higher precedence than the ||
但是,&&运算符的优先级高于||。 operator and should be evaluated first
运算符,应首先进行评估
No. Precedence doesn't affect execution ordering . 不会。优先顺序不会影响执行顺序 。 It's effectively bracketing.
这是有效的包围。 So your expression is equivalent to:
因此,您的表达式等效于:
boolean bool = (a = true) || ((b = true) && (c = true));
... which still executes a = true
first. ...仍然会先执行
a = true
。 At that point, as the result will definitely be true
and ||
到那时,结果肯定是
true
, ||
is short-circuiting, the right-hand operand of ||
短路时,
||
的右侧操作数 is not executed, so b
and c
are false. 未执行,因此
b
和c
为假。
From JLS section 15.7.1 : 从JLS第15.7.1节开始 :
The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.
在评估右侧操作数的任何部分之前,似乎已对二进制运算符的左侧操作数进行了完全评估。
Precedence is not relevant to that. 优先次序与此无关。
||
is short-circut so its right side will be evaluated only if at left will be false
. 是短循环的,因此只有在左侧为
false
才对右侧进行评估。
Because it performs lazy evaluation. 因为它执行惰性评估。
Since (a = true)
returns true
, (b = true) && (c = true)
is never evaluated. 由于
(a = true)
返回true
,因此(b = true) && (c = true)
不会被求值。 And hence you get such an output. 因此,您会得到这样的输出。
The && and || &&和|| operators are "short-circuit": they don't evaluate the right hand side if it isn't necessary.
操作员“短路”:如果不需要,他们不会评估右侧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.