Use the Safe Navigation Operator to Avoid Null Pointer Exceptions

Use the safe navigation operator (?.) to replace explicit, sequential checks for null references. This operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a NullPointerException.

If the left-hand-side of the chain expression evaluates to null, the right-hand-side is not evaluated. Use the safe navigation operator (?.) in method, variable, and property chaining. The part of the expression that is not evaluated can include variable references, method references, or array expressions.

So let’s take an example of a contact object record-

Contact contactObj = getContactRecord();
if(contactObj  != null) {
    system.debug(contactObj .FirstName);
}

So we can replace above code of block in a single line of statement as shown below using safe navigation operator (?.)-

system.debug(contactObj?.FirstName);

Other alternative:

system.debug(contactObj != null?contactObj.FirstName:null);

Published by Sandeep Kumar

He is a Salesforce Certified Application Architect having 11+ years of experience in Salesforce.

Leave a Reply