Given that example code:
boolean foo(String arg)
{
if( arg != null && arg.equalsIgnoreCase("bar") )
//Do something
}
Do I have guarantee that equalsIgnoreCase()
is only called if arg
is not null
?
Given that example code:
boolean foo(String arg)
{
if( arg != null && arg.equalsIgnoreCase("bar") )
//Do something
}
Do I have guarantee that equalsIgnoreCase()
is only called if arg
is not null
?
Yes, Java does offer short-cicuiting for conditionals, operating from left to right.
The conditional-and operator && is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
If the resulting value is
false
, the value of the conditional-and expression isfalse
and the right-hand operand expression is not evaluated.If the value of the left-hand operand is true, then the right-hand expression is evaluated; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8). The resulting value becomes the value of the conditional-and expression.
Yes, Java will guarantee that equalsIgnoreCase
is only called if arg
is not null. It will evaluate its operands from left to right, and in the case of &&
(and ||
), it will not evaluate the right operand if it doesn't need to evaluate it.
Section 15.23 of the JLS states:
The conditional-and operator && is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
and
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 false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated.