Sub topic 18
Ternary, ?., and ?? Operators
This chapter covers three Apex operators that make null-prone code shorter: the ternary operator ? :, the safe navigation operator ?., and the null coalescing operator ??. It assumes you know how Apex variables, null, and if statements work, and that you can run anonymous Apex in the Developer Console or an IDE.
The ternary operator
The ternary operator is an expression form of if/else. It has three parts: a condition, a value for true, and a value for false.
Integer score = 72;
String grade = score >= 60 ? 'Pass' : 'Fail';
System.debug(grade);Because it is an expression, it produces a value you can assign, pass to a method, or concatenate. Three rules matter:
- The condition must be a
Boolean. AnullBoolean throws aSystem.NullPointerExceptionwhen used as the condition. - Only the selected branch is evaluated. The other branch never runs.
- Both branches should produce compatible types, because the whole expression has one type.
Boolean flag = null;
String safe = (flag == true) ? 'on' : 'off';
System.debug(safe);Comparing with == true turns a null into false, so no exception is thrown.
Ternaries can be nested. They group from the right, so a ? x : b ? y : z means a ? x : (b ? y : z).
Integer n = 15;
String size = n < 10 ? 'small' : n < 100 ? 'medium' : 'large';
System.debug(size);Use a nested ternary only when it stays readable. More than two levels is usually clearer as an if/else if chain.
The safe navigation operator ?.
Reading a field or calling a method on a null reference throws a System.NullPointerException. The ?. operator checks the left side first. If it is null, the whole expression evaluates to null. Otherwise it behaves like a normal ..
Account acc = null;
String accountName = acc?.Name;
System.debug(accountName);The result is null, and no exception is thrown.
Chaining
Each ?. guards one step. This matters for relationship fields, which are null when the related record was not queried or does not exist.
Account acc = new Account(Name = 'Acme');
// acc.Owner is null here because no owner was loaded.
String ownerName = acc.Owner?.Name;
System.debug(ownerName);Writing acc.Owner.Name would throw. Note that acc.Owner?.Name guards only Owner. If acc itself could be null, write acc?.Owner?.Name.
Methods and collections
?. works on method calls too:
String text = null;
Integer len = text?.length();
System.debug(len);The result type follows the member you access. Here length() returns an Integer, so len can hold a number or null. Remember that an Integer variable can hold null. Arithmetic on that value later raises an error unless you handle it.
Limits
?. only reads. You cannot use it on the left side of an assignment, so acc?.Name = 'X' does not compile. It also does not hide other errors. Calling a method that itself throws still throws when the left side is non-null.
The null coalescing operator ??
The ?? operator returns its left operand if that operand is not null. Otherwise it returns the right operand.
String accountName = null;
String label = accountName ?? 'Unknown';
System.debug(label);This is a short form of accountName != null ? accountName : 'Unknown', and the left side is evaluated only once.
?? tests for null only. An empty string, 0, and false are all non-null, so they pass through unchanged.
String empty = '';
Integer zero = 0;
System.debug((empty ?? 'fallback') == '');
System.debug(zero ?? 99);The first line prints true and the second prints 0. If you want a fallback for blank strings too, use String.isBlank() with a ternary.
Map lookups
The most common use is a default for Map.get, which returns null for a missing key.
Map<String, Integer> stock = new Map<String, Integer>{ 'pens' => 10 };
Integer penQty = stock.get('pens') ?? 0;
Integer inkQty = stock.get('ink') ?? 0;
System.debug(penQty + ' ' + inkQty);Without ?? 0, inkQty would be null, and a later inkQty + 1 would throw.
Combining the operators
?. and ?? work well together. The first produces null safely, and the second replaces it with a default.
Account acc = null;
String accountName = acc?.Name;
String label = accountName ?? 'Unknown';
Integer score = 72;
String grade = score >= 60 ? 'Pass' : 'Fail';
System.debug(grade + ' ' + label);You can fold the first two steps into one expression: String label = acc?.Name ?? 'Unknown';.
The diagram below shows how acc?.Name ?? 'Unknown' is evaluated.
Precedence and grouping
Among these operators, ?? binds more loosely than arithmetic, comparison, &&, and ||. The ternary operator binds more loosely still, and assignment is the loosest. So a ?? b + 1 means a ?? (b + 1), not (a ?? b) + 1. When the intent is not obvious, add parentheses:
Integer bonus = null;
Integer total = 10 + (bonus ?? 0);
System.debug(total);Without the parentheses, 10 + bonus ?? 0 would add null to 10 first and throw.
Common mistakes
- Using
??to test for blank strings. It does not treat''as missing. - Guarding only the last step of a chain, as in
acc.Owner?.Namewhenaccmay benull. - Using a possibly
nullBooleanas a ternary condition. - Assuming
?.makes the result non-null. It makesnullpossible, so pair it with??or a later check.
Exercise
What does this code print, and why? Map<String, String> m = new Map<String, String>{ 'a' => '' }; System.debug(m.get('a') ?? 'none'); System.debug(m.get('b') ?? 'none');
Show answer
It prints an empty line, then none. The value for key 'a' is an empty string, which is not null, so ?? returns it unchanged. Key 'b' is missing, so get returns null and ?? returns 'none'.
Exercise
Rewrite String city = acc.Owner.Name; so it cannot throw when acc or acc.Owner is null, and so city is 'n/a' in that case.
Show answer
String city = acc?.Owner?.Name ?? 'n/a';