Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java evaluate remaining conditions after boolean result is known?

Tags:

java

That is, if I have a statement that evaluates multiple conditions, in say a 'or' statement like so..

if(isVeryLikely() || isSomewhatLikely() || isHardlyLikely()) {     ... } 

In the case that isVeryLikely() returns true at runtime, will isSomewhatLikely() and isHardlyLikely() execute? How about if instead of methods they were static booleans?

like image 346
P. Deters Avatar asked Jun 15 '11 01:06

P. Deters


People also ask

How are if conditions evaluated in Java?

At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (§5.1. 8). If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated.

Does Java evaluate right to left?

Order of operand evaluation in Java. In Java, the operands of an operator are always evaluated left-to-right.

How is boolean related to if else condition?

The if statement will evaluate whatever code you put in it that returns a boolean value, and if the evaluation returns true, you enter the first block. Else (if the value is not true, it will be false, because a boolean can either be true or false) it will enter the - yep, you guessed it - the else {} block.

Which expression evaluates to true in Java?

These operators include equality ( == ) and inequality ( != ). The former operator returns true when both operands are equal; the latter operator returns true when both operands are unequal.


1 Answers

The || and && operators are short-circuiting.

true || willNeverExecute(); false && willNeverExecute(); 
like image 80
Chris Jester-Young Avatar answered Oct 17 '22 19:10

Chris Jester-Young