Sub topic 4
Working with null
This chapter explains what null means in Apex, which operations tolerate it, which ones throw an exception, and how to write code that handles it deliberately. It assumes you can declare variables and write if statements in Apex. You should also know that a Salesforce field with no value comes back empty. You can run every example in Anonymous Apex in the Developer Console.
What null means
null means "no value". A variable of any type can hold it: a String, an Integer, a Boolean, a List, or an SObject. A variable you declare without assigning a value starts as null. This is true for numbers and Booleans too, so Apex has no default of 0 or false.
String note;
Integer total;
Boolean flag;
List<Integer> items;
System.debug(note == null);
System.debug(total == null);
System.debug(flag == null);
System.debug(items == null);All four lines print true.
null is different from an empty value. An empty string '' and an empty list new List<Integer>() are real objects with nothing in them. A null list is no object at all. Calling a method on it fails, while calling a method on an empty list works.
Where null causes exceptions
Dereferencing a null value means calling a method on it, reading a field from it, or using it in arithmetic. Any of these throws a System.NullPointerException with the message "Attempt to de-reference a null object".
Integer a = 5;
Integer b = null;
try {
Integer c = a + b;
System.debug(c);
} catch (NullPointerException e) {
System.debug(e.getMessage());
}
System.debug('Total: ' + b);The addition throws, because arithmetic needs two real numbers. The string concatenation does not throw. It prints Total: null, because + with a String converts null to the text "null". This is a common way for the word "null" to end up in user-facing text.
Other operations that throw on null:
- Calling a method on a
nullvariable, such asnote.toUpperCase()oritems.size(). - Reading a field from a
nullSObject, such asacc.Namewhenaccisnull. - Using a
nullBooleanas a condition, as inif (flag)or!flag. - Compound assignment on a
nullnumber, such astotal += 1.
Comparing with null
== and != work safely with null on either side. Two null values are equal, and a non-null value is never equal to null.
Boolean flag;
System.debug(flag == null);
System.debug(flag == true);
System.debug(flag == false);
try {
if (flag) {
System.debug('never reached');
}
} catch (NullPointerException e) {
System.debug('Boolean null in a condition throws');
}A Boolean can be true, false, or null, so it has three states. Writing flag == true is a safe way to treat null as "not true". The first two comparisons print true and false. flag == false also prints false, so null is neither true nor false.
Relational operators (<, >, <=, >=) are less obvious. Salesforce documents them as returning false when either side is null for Integer, Double, Date, and Datetime. Don't build logic on that behavior. Check for null first so the intent is visible.
Null inside collections
A Map returns null from get when the key is missing. That is the same result you get when the key exists but its value is null. Use containsKey when the two cases matter.
Map<String, Integer> stock = new Map<String, Integer>{ 'pens' => 10 };
Integer qty = stock.get('missing');
System.debug(qty == null);
System.debug(stock.containsKey('missing'));
Integer safeQty = stock.get('missing') ?? 0;
System.debug(safeQty);This prints true, false, and 0. Lists and sets can hold null elements, and a map can use null as a key. These are legal but rarely intended. A null element often means a lookup failed earlier in the code.
A collection variable that is itself null is a bigger problem than a collection that holds nulls. Initialize collections where you declare them:
List<String> names = new List<String>();
names.add('Ada');
System.debug(names.size());SObject fields: null versus not queried
A field you queried that has no value is null. A field you did not include in the SOQL query is different. Reading it throws a System.SObjectException, not a NullPointerException. The two errors look similar but have different causes. One means "the data is empty" and the other means "you never asked for the data".
An SObject variable can also be null. A SOQL query assigned to a single SObject throws a QueryException when it finds no rows, so a null check does not help there. Query into a List and check isEmpty() instead.
Handling null on purpose
Apex gives you four main tools.
| Tool | Example | Behavior |
|---|---|---|
| Explicit check | `if (acc != null)` | Runs the block only when a value exists |
| Safe navigation `?.` | `acc?.Name` | Returns `null` instead of throwing when `acc` is `null` |
| Null coalescing `??` | `qty ?? 0` | Returns the left side if it is not `null`, otherwise the right side |
| String helpers | `String.isBlank(s)` | Returns `true` for `null`, `''`, and whitespace |
You can combine ?. and ??:
Account acc = null;
System.debug(acc?.Name);
System.debug(acc?.Name ?? 'Unknown');
String input = null;
System.debug(String.isBlank(input));
System.debug(String.isEmpty(input));This prints null, Unknown, true, and true. isEmpty treats only null and '' as empty. isBlank also treats whitespace-only strings as blank, which is usually what you want for user input.
The diagram shows how to pick an approach.
Common mistakes
- Assuming a number defaults to 0.
Integer count;isnull, socount++throws. WriteInteger count = 0;. - Using
!flagon a nullable Boolean. It throws whenflagisnull. Compare with== trueor== false. - Concatenating a null into text. You get the literal word "null". Use
value ?? ''when you build messages. - Using
getto test for a key. It cannot tell a missing key from a storednull. UsecontainsKey. - Checking for null too late. Test before the dereference, not after. In
acc != null && acc.Name == 'X'the first test protects the second. If you swap them, the code throws.
Exercise
Given Integer qty; Map<String, Integer> stock = new Map<String, Integer>();, which of these throws at runtime: (1) Integer x = qty + 1; (2) Integer y = (stock.get('a') ?? 0) + 1; (3) String s = 'Qty: ' + qty;? State the result of each.
Show answer
Only (1) throws, because qty is null and arithmetic dereferences it, raising a NullPointerException. (2) works: stock.get('a') is null, ?? substitutes 0, and y is 1. (3) works and produces Qty: null, because string concatenation converts null to the text "null".
Exercise
A method receives List<Account> accs that may be null. Write a loop-safe check so the method returns 0 when accs is null or empty, otherwise accs.size().
Show answer
if (accs == null || accs.isEmpty()) { return 0; } return accs.size(); The || short-circuits, so isEmpty() is never called when accs is null.