Every Salesforce Developer has seen it: System.NullPointerException. Let's break
down why
this happens and how to stop it.
In Apex, null is a literal that represents a variable that
exists but has **no value assigned**. It is a point in memory that leads to nowhere.
The most common error is the **NullPointerException (NPE)**. This occurs when you try to access a field or method on a variable that is null.
5 + null will crash your
transaction.
if (isactive) check fails
if isactive is null.
.add() on a list that
wasn't initialized.
| Data Type | Behavior if Null |
|---|---|
| String | Different from empty string "". |
| Decimal | Cannot be used in math without a check. |
| SObject | Fields return null if record is not found. |
Safe Navigation Operator (?.)
String name = myAccount?.Name;
Stops the crash and returns null instead of an error.
The Standard Null Check
if (myList != null && !myList.isEmpty()) { ... }
Always verify data exists before looping.
Compare the "Dangerous" approach with the "Professional" solution.
Instead of writing long if/else chains to check for nulls, use
the
Safe Navigation Operator (?.). It stops the execution if
the variable is null
and returns null instead of throwing a crash.
In Apex, simply declaring a List is not the same as creating one. Until you use the new keyword, your variable is just a label pointing to "nothing".
Null (Declared)
You have a reservation for a table, but the restaurant hasn't actually set the table yet. There is no physical place to sit.
Empty (Instantiated)
The table is set and ready. Even if no one is sitting there yet, the space is allocated and ready for guests (data).
In your provided code, you might expect the "No Site" debug to run, but it won't. Here is why '' is not the same as null.
Result: "Site has been published"
Result: "NO Site has been published"
To catch both null AND '', Salesforce developers use the String.isBlank() method.
Can you spot the Null Pointer before it crashes the system?
You are incrementing a counter on an Account. If the field Total_Contacts__c is currently empty (null), what happens?
Result: System.NullPointerException ❌
You cannot perform math on a null value.
The Professional Fix:
You query for a single Lead by email. What happens if no Lead matches that email?
Result: System.QueryException ❌
Assigning a query to a single variable fails if 0 rows are returned.
The Professional Fix: