12 < 6 && 18 > 1 evaluates to false
| AND Operator && | |
|---|---|
true && true | true |
false && true | false |
true && false | false |
false && false | false |
You may have noticed something in answering the question: you can get the correct answer to the question by evaluating just the first part of the expression:
12 < 6 && 18 > 1 ------ false
Since false && anything is false,
there is no need
to continue after the
first false has been evaluated.
In fact,
this is how Java operates:
To evaluateX && Y, first evaluate X. If X isfalsethen stop: the whole expression isfalse. Otherwise, evaluate Y then AND the two values.
This idea is called short-circuit evaluation.
Programmers frequently make use of this feature.
For example,
say that two methods that return true/false values
are combined in a boolean expression:
if ( methodThatTakesHoursToRun() && methodThatWorksInstantly() ) doSomething();
Suggest a better (but logically identical) way to arrange this boolean expression.