ApexSensei

Drills Apex basics

Safe navigation with ?.

Apex basics · Beginner · 12 min · Runs in your Salesforce Developer org · Free

Write `cityOrDefault(Account acct, String fallback)` that returns the Account's `BillingCity`, or the fallback when either the Account or the city is `null`. Use the safe navigation operator `?.` to avoid a null-pointer crash, and the null-coalescing operator `??` to pick the fallback. One line is enough.

Lesson

Why this matters

Salesforce code reads fields off objects all day long. If the object is null, every dot throws a NullPointerException and the whole transaction dies. The safe navigation operator ?. was added so you can read a field without first writing an if guard every time.

The smallest working example

Account acct = null;
String city = acct?.BillingCity ?? 'Unknown';

city is 'Unknown' because acct is null, so acct?.BillingCity is null, and ?? picks the right side.

Name the parts

  • **?.** reads the field only if the left side is not null; otherwise the whole expression is null. No throw.
  • **??** is Apex's null-coalescing operator. left ?? right returns left when it is not null, and right otherwise.
  • **An empty string '' is not null.** ?? does not swap it. If you want to swap empty strings too, use String.isBlank.

A common wrong version

String city = acct.BillingCity != null ? acct.BillingCity : fallback;

For acct = null, the first acct.BillingCity throws before the ternary even runs. The whole script dies.

The fix

return acct?.BillingCity ?? fallback;

Safe for acct = null, safe for an unset BillingCity, and lets a real empty string pass through.

Now you try

Return that one expression from cityOrDefault. The grader tries real cities, a null Account, an unset city and an empty-string city.

Learn more

The challenge

Write cityOrDefault(Account acct, String fallback) that returns the Account's BillingCity, or the fallback when either the Account or the city is null.

Examples:

  • cityOrDefault(new Account(BillingCity = 'Austin'), 'Unknown') → Austin
  • cityOrDefault(null, 'Unknown') → Unknown
  • cityOrDefault(new Account(BillingCity = ''), 'Unknown') → `` (empty is not null)

Requirements:

  1. cityOrDefault with BillingCity = 'Austin' should be Austin.
  2. cityOrDefault(null, 'Unknown') should be Unknown.
  3. cityOrDefault(new Account(), 'Unknown') should be Unknown.
  4. cityOrDefault with BillingCity = '' should be an empty string.
  5. cityOrDefault(null, 'N/A') should be N/A.
  6. cityOrDefault with BillingCity = 'NYC' should be NYC.
  7. cityOrDefault(null, '') should be an empty string.

Starter code

String cityOrDefault(Account acct, String fallback) {
    return null;
}

Related drills

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Combine conditions with && and || · break and continue ›