In the release of Spring ’24, Salesforce introduced a new feature, the Coalescing Null operator. This operator combines multiple null checks to avoid null pointer exceptions and eliminates the need for multiple if-else conditional blocks.
In this Salesforce tutorial, I will explain the Coalescing Null operator in Salesforce Apex and demonstrate how to coalesce null values in Salesforce Apex and within SOQL queries.
What is a Null Coalescing Operator in Salesforce?
In Salesforce, we use NULL operators to avoid null pointer exceptions. Ideally, we should add multiple if-else blocks in the code if there are multiple Null pointers.
To avoid creating multiple code blocks, we use the Null coalescing operator in the form of a ?? b that returns a if it isn’t null and otherwise returns b.
When we have to check and return null values across multiple fields in SOQL queries, we indirectly use the formula field to coalesce the null field values.
So, the Null Coalescing Operator (??) is used in Apex to return the first non-null value between two operands. We can use conditionals to replicate the null coalescing operator in SOQL.
Use the Null Coalescing Operator in Salesforce Apex
To use the binary null coalescing operator in the Salesforce Apex code, we use it in the form “value1 ?? value2”.
Let’s understand with an example where we can conditionally assign values based on whether a variable is null and how to handle both cases in Apex using the if/else conditionals.
Integer intValue = 10;
Integer outputValue;
if(intValue != null) {
outputValue = intValue;
}
else {
outputValue = 0;
}
System.debug('outputValue is '+outputValue);
Output:

Handling Null values for multiple fields:
When we need to handle null values for multiple fields, we must define multiple if-else blocks, as shown in the code below.
Integer outputVal;
Integer a = 10;
Integer b = 20;
Integer c = 60;
Integer d = 85;
if(a != null) {
outputVal = a;
}
else if(b != null) {
outputVal = b;
}
else if(c != null) {
outputVal = c;
}
else if(d != null) {
outputVal = d;
}
else{
Integer outputVal = 100;
}
System.debug('Output value is '+outputVal);
To handle null value pointers in the Integer values of a, b, c, and d. If all the values are null, it will return the default integer value of 100.
We can reduce the lines of code in the above Apex code by using the null coalescing operator (??) to check the null references in the code.
Follow the code below to use the null coalesce operator in Salesforce Apex.
Integer num1 = null;
Integer num2 = 10;
Integer num3 = 30;
Integer num4 = 40;
Integer outputVal = num1 ?? num2 ?? num3 ?? num4 ?? 100;
System.debug('Output value is ' + outputVal);
This will handle the null pointers for all the above-mentioned integer values. In this example, I have entered ‘num1‘ as null, so the desired output is 10.
Output:
