Java provides a conditional-and and a conditional-or operator, that both take one or two operands of type boolean and produce a boolean result. These are:
&& - the conditional-AND operator,|| - the conditional-OR operators. The evaluation of <left-expr> && <right-expr> is equivalent to the following pseudo-code:{
boolean L = evaluate(<left-expr>);
if (L) {
return evaluate(<right-expr>);
} else {
// short-circuit the evaluation of the 2nd operand expression
return false;
}
}
The evaluation of <left-expr> || <right-expr> is equivalent to the following pseudo-code:
{
boolean L = evaluate(<left-expr>);
if (!L) {
return evaluate(<right-expr>);
} else {
// short-circuit the evaluation of the 2nd operand expression
return true;
}
}
As the pseudo-code above illustrates, the behavior of the short-circuit operators are equivalent to using if / else statements.
The following example shows the most common usage pattern for the && operator. Compare these two versions of a method to test if a supplied Integer is zero.
public boolean isZero(Integer value) {
return value == 0;
}
public boolean isZero(Integer value) {
return value != null && value == 0;
}
The first version works in most cases, but if the value argument is null, then a NullPointerException will be thrown.
In the second version we have added a “guard” test. The value != null && value == 0 expression is evaluated by first performing the value != null test. If the null test succeeds (i.e. it evaluates to true) then the value == 0 expression is evaluated. If the null test fails, then the evaluation of value == 0 is skipped (short-circuited), and we don’t get a NullPointerException.
The following example shows how && can be used to avoid a relatively costly calculation:
public boolean verify(int value, boolean needPrime) {
return !needPrime | isPrime(value);
}
public boolean verify(int value, boolean needPrime) {
return !needPrime || isPrime(value);
}
In the first version, both operands of the | will always be evaluated, so the (expensive) isPrime method will be called unnecessarily. The second version avoids the unnecessary call by using || instead of |.