Sometimes your code needs to pick between exactly two values. The ternary operator lets you make that choice in a single expression:
condition ? valueIfTrue : valueIfFalse
Apex evaluates the condition first. When the condition is true, the whole expression becomes the first value. When it is false, the expression becomes the second value.
An if/else statement performs actions, but it does not produce a value. The ternary operator is an expression: it produces a value that you can store in a variable or return from a method.
Integer temperature = 30; String weather = temperature > 25 ? 'Hot' : 'Mild'; System.debug(weather); // Hot
These two blocks of code do exactly the same thing:
// Using if/else
String label;
if (temperature > 25) {
label = 'Hot';
} else {
label = 'Mild';
}
// Using the ternary operator
String label2 = temperature > 25 ? 'Hot' : 'Mild';
The ternary version expresses the same choice in one line.
Reach for the ternary operator when you have a simple two-way choice between two values. Avoid nesting one ternary inside another: nested ternaries are hard to read, and a plain if/else is much clearer in those cases.
// Hard to read - do not do this String size = value > 100 ? 'Large' : value > 50 ? 'Medium' : 'Small';