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;
}
Java uses Lazy evaluation.
Since Func1 always returns true, the entire expression MUST be true, so it shortcuts the rest of the expression.
and
will always shortcut.
To turn off shortcut evaluation, use | and & instead of || and &&
We can use this to good effect:
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
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:
After func1 returns, it becomes this:
After evaluating the short-circuited or, it becomes:
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.