Sub topic 4
Working with null
This chapter assumes you can declare variables and know the primitive types from the previous chapters. It covers what null means in Apex, where it shows up, and how to avoid the errors it causes.
What null means
null means "no value." A variable that has been declared but not assigned holds null. This is true for every type, including Integer, Boolean, and collections. Apex does not default numbers to 0 or booleans to false.
String note;
System.debug(note == null);
Integer total = null;
System.debug(total == null);Both lines print true. Use == null or != null to test for it.
Where null appears
- Variables that were declared but never assigned.
- Fields on an SObject record that were not set or not queried.
- The result of
Map.getwhen the key is not in the map. - Variables you assigned
nullyourself.
Map<String, Integer> stock = new Map<String, Integer>{ 'pens' => 10 };
System.debug(stock.get('pens'));
System.debug(stock.get('missing'));The second call prints null. It does not throw an error. If you then use that result in arithmetic, the error appears later and farther from its cause.
How null behaves in expressions
| Expression | Result |
|---|---|
| `null == null` | `true` |
| `'a' == null` | `false` |
| `String s = null; s + 'x'` | `'nullx'` (concatenation converts null to text) |
| `Integer n = null; n + 1` | `System.NullPointerException` |
| `Boolean b = null; if (b) {...}` | `System.NullPointerException` |
| `List<Integer> items = null; items.size()` | `System.NullPointerException` |
Calling a method on a null reference, or using a null value in arithmetic or as a condition, throws a NullPointerException. Treat a Boolean as having three states: true, false, and null. A null Boolean is neither true nor false.
Guarding against null
Check before you use a value. The && operator stops evaluating as soon as the left side is false, so the right side is never reached.
Boolean hasValue = false;
List<Integer> items = null;
if (items != null && !items.isEmpty()) {
hasValue = true;
}
System.debug(hasValue);Because items != null is false, items.isEmpty() never runs. If you reversed the two conditions, this code would throw. A later chapter covers the ?. and ?? operators, which shorten many of these checks.
Common mistakes
- Assuming an uninitialized
Integeris0. It isnull. - Calling
.size()or.add()on a collection you declared but never created withnew. - Using a null
Booleandirectly in anif. - Reading the result of
Map.getwithout checkingcontainsKeyor testing for null.
Exercise
What happens when this code runs, and why? Integer count; Integer next = count + 1;
Show answer
It throws a System.NullPointerException. count is declared but not assigned, so it holds null, not 0, and null cannot be used in arithmetic. Initialize it with Integer count = 0; or check count != null first.