What is wrong with the short circuit logic in this

2020-04-03 12:55发布

Why doesn't func3 get executed in the program below? After func1, func2 doesn't need to get evaluated but for func3, shouldn't it?

if (func1() || func2() && func3()) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }
}

public static boolean func1() {
    System.out.println("func1");
    return true;
}

public static boolean func2() {
    System.out.println("func2");
    return false;
}

public static boolean func3() {
    System.out.println("func3");
    return false;
}

9条回答
Melony?
2楼-- · 2020-04-03 13:37

Java uses Lazy evaluation.

Since Func1 always returns true, the entire expression MUST be true, so it shortcuts the rest of the expression.

true || (???)

and

false && (???)

will always shortcut.

To turn off shortcut evaluation, use | and & instead of || and &&

We can use this to good effect:

String s;
if (s != null && !s.equals("")) ...

Meaning that if s is null, we won't even have to try to call s.equals, and we won't end up throwing an NullPointerException

查看更多
老娘就宠你
3楼-- · 2020-04-03 13:39

You're using a short-circuited or. If the first argument is true, the entire expression is true.

It might help if I add the implicit parentheses that the compiler uses

Edit: As Chris Jester-Young noted, this is actually because logical operators have to left-to-right associativity:

if (func1() || (func2() && func3()))

After func1 returns, it becomes this:

if (true || (func2() && func3()))

After evaluating the short-circuited or, it becomes:

if (true)
查看更多
做自己的国王
4楼-- · 2020-04-03 13:45

If function 1 always returns true, then Java doesn't need to evaluate the rest of the expression to determine that the whole expression will be true.

查看更多
登录 后发表回答