I’m wondering if it’s guaranteed that in a Java program, the boolean expression on the right of a conjunction (exp2 above) will NOT be evaluated as long as the expression on the left (exp1) evaluated to false. I’m wondering because I have an expression like the following:
if (var != null && var.somePredicate())
// do something
If Java is not guaranteed to stop evaluating (var != null && var.somePredicate()) after it sees that var is null, then it may try to evaluate var.somePredicate() which would throw a NullPointerException.
So my question is, does Java guarantee a certain behavior when it comes to this? Or would it be safer to write
if (var != null)
{
if (var.somePredicate())
// do something
}
From the Java Language Specification, 15.23 Conditional-And Operator &&:
So the language spec guarantees that the right-hand side of your expression will not be evaluated if the left hand side is false.