5

I want to write an if condition like

if(a!=null && a.id!=null)

I want to make sure that the second part is completely ignored (otherwise nullpointer exception will be thrown) so I can put both conditions in one line instead of doing something like

if(a!=null){
   if(a.id!=null){
   }
}

This document says two sides of "&&" cannot be null. How can I do this?

1
  • 1
    You seem to be partially referring to Short Circuit Evaluation which a number of programming languages use. Essentially, if the first value in the logical AND is false, there is no need to evaluate the second, and the statement evaluates to false. Oct 26 '16 at 13:56
6

You've slightly misunderstood that documentation.

The documentation for the logical and operator && says that in the expression x && y, neither x nor y can be null.

However, there is a difference between being null and checking for null.

a != null and a.Id != null are both expressions that return boolean values. These expressions can have null appear in them without issue. The only time you'd run into a problem here is if you were to check a.Id != null before checking if a is null.

If a is null, the expression fragment a.Id would translate to null.Id, and you'd get a null pointer exception.

Battery.cord's and Jesse Milburn's comments on short circuit evaluation are also good to keep in mind. The reason why this null-checking pattern works is because of short-circuit evaluation.

if a is null, then your expression becomes if(false && a.Id != null). From Boolean logic/algebra, false && x == false. There becomes no need to evaluate the second part of your expression, so Salesforce doesn't evaluate it.

tl;dr:

if(a != null && a.Id != null) is perfectly legal.

1
  • As an aside, you can avoid short circuit evaluation (e.g. to call methods with side effects) by using bitwise operators (& or |), which helpfully can take two Boolean variables in addition to numeric types. Oct 26 '16 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.