Null: The Concept of Nothing
By the end of this lesson, you'll be able to:
- Explain what null represents
- Distinguish null from a default or empty value
- Write a basic null check before using a variable
Prerequisites: "A First Look at Non-Primitive Types"
Null is not the same as empty or zero
Integer count; // null — never assigned
Integer zeroCount = 0; // 0 — a real, assigned value
String name; // null
String emptyName = ''; // '' — a real, assigned (empty) value
An uninitialized variable defaults to null — Apex's way of saying "this box exists, but nothing has been put in it yet." Zero and empty string are both real values; null is the absence of any value.
A real business example: Insurance
Decimal claimAmount; // not yet set — null
if (claimAmount != null) {
System.debug('Claim amount: ' + claimAmount);
} else {
System.debug('No claim amount recorded yet.');
}
An insurance claim that hasn't been assessed yet genuinely has no amount — not zero, which would incorrectly suggest "assessed, and worth nothing." Null correctly represents "not yet known."
Common mistakes
- Using a variable without checking for null first. Calling a method on a null variable (like
.toUpperCase()on a null String) throws aNullPointerException— one of the single most common runtime errors in all of Apex. - Confusing null with zero in numeric logic. A null
Decimalused in arithmetic will throw an error, not silently act like zero.
The classic null pointer mistake
String customerNotes;
System.debug(customerNotes.toUpperCase()); // throws NullPointerException!
customerNotes was declared but never assigned, so it's null. Calling any method on null blows up immediately — always check for null first when a value might not be set.
Exercise
Declare a String called middleName without assigning it a value. Write an if statement that debugs 'No middle name on file.' if it's null, or the name itself otherwise.
Show hint
if (middleName == null) { ... } else { ... }
Null: The Concept of Nothing Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Null means "no value at all" — not zero, not an empty string, but the complete absence of a value. Understanding null early prevents one of the most common runtime errors in Apex: the null pointer exception.