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 notnull; otherwise the whole expression isnull. No throw. - **
??** is Apex's null-coalescing operator.left ?? rightreturnsleftwhen it is notnull, andrightotherwise. - **An empty string
''is notnull.**??does not swap it. If you want to swap empty strings too, useString.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')→AustincityOrDefault(null, 'Unknown')→UnknowncityOrDefault(new Account(BillingCity = ''), 'Unknown')→ `` (empty is not null)
Requirements:
cityOrDefaultwithBillingCity = 'Austin'should beAustin.cityOrDefault(null, 'Unknown')should beUnknown.cityOrDefault(new Account(), 'Unknown')should beUnknown.cityOrDefaultwithBillingCity = ''should be an empty string.cityOrDefault(null, 'N/A')should beN/A.cityOrDefaultwithBillingCity = 'NYC'should beNYC.cityOrDefault(null, '')should be an empty string.
Starter code
String cityOrDefault(Account acct, String fallback) {
return null;
}
Related drills
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.