When Java calculates a conjunction (\ u0026 \ u0026), if Exp1 is false, does it Eval exp2?

I want to know whether to ensure that in Java programs, as long as the expression on the left (Exp1) evaluates to false, the Boolean expression on the right of the connection (exp2 above) will not be evaluated I want to know because I have the following expression:

if (var != null && var.somePredicate())
   // do something

If Java cannot guarantee to stop evaluation after seeing that VaR is null (VaR! = null & & var.somepredict()), it may try to evaluate var.somepredict(), which will cause NullPointerException

So my question is, does Java guarantee some behavior in this regard? Or it's safer to write

if (var != null)
{
   if (var.somePredicate())
      // do something
}

Solution

From Java language specification, 15.23 conditional and operator & &:

Therefore, the language specification guarantees that if the left side is false, the right side of the expression will not be evaluated

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>