Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
Salesforce Developer
medium

How does Apex handle null values, and what patterns help avoid NullPointerException?

Apex's null semantics are mostly Java-like, with some Salesforce-specific quirks.

What is null:

  • Variables declared but uninitialised: String s; is null.
  • sObject fields not selected in SOQL come back as null — even if they have values in the DB.
  • Empty collections are NOT null — new List<Account>() is empty but non-null.
  • null returns true for == against another null.

NullPointerException sources:

  • Calling a method on null: acc.Name.toLowerCase() when acc or acc.Name is null.
  • Dereferencing a map's value when key not present: myMap.get(badKey).fieldget() returns null, then dereferencing fails.
  • SOQL returning empty list, then .get(0) on it — IndexOutOfBoundsException, not NPE, but similar pattern.

Patterns to avoid NPEs:

  1. Safe navigation operator (Apex equivalent: ?.):

apex String name = acc?.Account?.Name;

  1. Null check before access:

apex if (acc != null && acc.Name != null) { ... }

  1. Default values via `.get(key, defaultValue)` — Map's get with default.
  1. String.isBlank() / String.isEmpty() — check string-ness without NPE.
  1. `List.isEmpty()` before accessing element by index.
  1. Null-coalescing for primitives:

apex Decimal amount = opp.Amount == null ? 0 : opp.Amount;

The single biggest source of NPEs in Apex is querying with LIMIT 1 and then accessing the result without checking if the list is empty.

Why this answer works

Tests defensive coding. The safe-navigation operator (which Apex added relatively recently) and the "LIMIT 1 trap" are strong signals.

Follow-ups to expect

Related dictionary terms