Does Java evaluate remaining conditions after boolean result is known?
The ||
and &&
operators are short-circuiting.
true || willNeverExecute();
false && willNeverExecute();
Because the || is short circuiting, the statement will be evaluated to true as soon as it hits the first true condition, regardless of whether or not the operands are static.
In short, no the two other functions will not be evaluated if the first returns true.
The first thing that you need to note is that Java conditional statements can only take boolean, unlike other languages like C/C++ where any non-zero value will evaluate to true.
That being said, there are 2 types of operators, the first is known as the shor-circuit types:
&& and ||
while the other are the NON-short-circuit types:
& and |
For the Short-Circuit types, once a logical output can be found as an answer to the expression, the rest of the statement will be dumped. For the NON-Short-Circuit types, they will continue to evaluate all conditions.
With this in mind, what you have:
if(isVeryLikely() || isSomewhatLikely() || isHardlyLikely())
{
...
}
Java will:
- First check if isVeryLikely() returns true. If true, then it will not continue further.
- If isVeryLikely() returns false, then invoke isSomewhatLikely() to see if it returns true. If true, nothing else if evaluated. If false, goto 3.
- isHardlyLikely() is invoked. If true, entire expression is true, otherwise false, entire expression is false.
The entire concept you're asking about is "How does Java evaluate Logical Expressions." Good question :)
Hope it helps! Cheers!
No, java uses short-circuit evaluation on expressions using ||
and &&
. See here for more info.