Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

conditional - When Java evaluates a conjunction (<boolean exp1> && <boolean exp2>), does it eval exp2 if exp1 is false?

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the Java Language Specification, 15.23 Conditional-And Operator &&:

The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.

So the language spec guarantees that the right-hand side of your expression will not be evaluated if the left hand side is false.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...