简体   繁体   English

为什么这不短路?

[英]Why does this not short circuit?

public static void main(String args[]){
    String s = null;

    if(false && false || s.equalsIgnoreCase("x")) {    //throws an exception
        System.out.println("true");
    } else {
        System.out.println("false");
    }
}

I was expecting after this encounters false to short circuit but it doesn't. 我原以为这会遇到短路故障,但事实并非如此。 Why is that? 这是为什么? I assumed if you have a false there is NO need to proceed to the next &&. 我假设如果您有错误,则无需继续下一个&&。 Please help me to understand. 请帮助我理解。

Because this: 因为这:

a && b || c

is equivalent to this: 等效于此:

(a && b) || c

The lhs of the || ||的lhs is false, so c gets evaluated. 为假,因此对c求值。

The && operator has higher precedence than the || &&运算符的优先级高于|| operator . 操作员 So, the condition is equivalent to 因此,条件等于

if( (false && false) || s.equalsIgnoreCase("x")) {    //throws an exception

which is then evaluated to leave: 然后评估离开:

if(false || s.equalsIgnoreCase("x")) {    //throws an exception

which doesn't short circuit. 这不会短路。 To make it short-circuit, use parentheses: 要使其短路,请使用括号:

if(false && (false || s.equalsIgnoreCase("x"))) {    // fine

The and have higher precedence so it's bracketed like 和具有较高的优先级,因此将其括起来

((false && false) || s.equalsIgnoreCase("x"))

(false && false) reduces to false which is not short-circuit by || (false && false)减少为false ,不会因||短路 .


It's worth remembering that & is sort of like * ( 1 & 1 = 1 and 0 * 1 = 1 ) and + is sort of like | 值得记住的是, &有点像*1 & 1 = 10 * 1 = 1 ),而+有点像| hence & have higher precedence. 因此&具有更高的优先级。 In maths sometimes + is used as or and nothing for both & and * . 在数学中,有时+用作or,而&* Logic operations have the same precedence as binary ones so && have higher then || 逻辑运算的优先级与二进制运算的优先级相同,因此&&优先级高于|| .

Why should it short-circuit? 为什么要短路? || || only short-circuits if the LH operand is true. 仅当LH操作数为true时才短路。 && short-circuits if the LH operand is false. 如果LH操作数为false,则&&短路。 Here you have a short-circuing && and a non-short-circuiting ||. 在这里,您有一个短路&&和一个非短路||。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM