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 short-circuits boolean expressions. That means that, once
func1()
is executed and returnstrue
, the rest of that boolean doesn't matter since you are using anor
operator. No matter whatfunc2() && func3()
evaluates to, the whole expression will evaluate totrue
. Thus, Java doesn't even bother evaluating thefunc2()
orfunc3()
.If you want all functions to be executed you can drop the short-cut variants
Java functions are evaluated according to precedence rules
because "&&" is of higher precendence than "||", it is evaluated first because you did not have any brackets to set explicit precedence
so you expression of
which is
is bracketed as
because of the precedence rules.
Since the compiler understands that if 'A == true' it doesn't need to bother evaluating the rest of the expression, it stops after evaluating A.
If you had bracketed
((A || B) && C)
Then it would evaluate to false.EDIT
Another way, as mentioned by other posters is to use "|" and "&" instead of "||" and "&&" because that stops the expression from shortcutting. However, because of the precedence rules, the end result will still be the same.
You're using the shortcut-operators || and &&. These operators don't execute the rest of the expression, if the result is already defined. For || that means if the first expression is true and for && if the first expression is false.
If you want to execute all parts of the expression use | and & instead, that is not shortcut.
short answer: short-circuit evaluation
since func1() yelds true there is not need to continue evaluation since it is always true
http://en.wikipedia.org/wiki/Short-circuit_evaluation