The Ternary Operator
By the end of this lesson, you'll be able to:
- Write a short conditional assignment using the ternary operator
- Rewrite a simple if/else as a ternary expression
- Recognize when a ternary hurts readability instead of helping
Prerequisites: "Switch Statements"
The shape
Integer stock = 3;
String stockLabel = stock > 0 ? 'In Stock' : 'Out of Stock';
Integer stock = 3;— the quantity on hand.String stockLabel = stock > 0 ? 'In Stock' : 'Out of Stock';— read the? :part as "ifstock > 0, use'In Stock'; otherwise use'Out of Stock'." Since3 > 0is true,stockLabelbecomes'In Stock'.
This is functionally identical to:
String stockLabel;
if (stock > 0) {
stockLabel = 'In Stock';
} else {
stockLabel = 'Out of Stock';
}
String stockLabel;— declared, not yet assigned.if (stock > 0) {—true.stockLabel = 'In Stock';— runs, assigning the value.} else {— never reached.stockLabel = 'Out of Stock';— skipped.}— closes theif/else.
— just four lines shorter, for exactly this simple case.
A real business example: Case Management
Integer priority = 1;
String urgencyLabel = priority == 1 ? 'Urgent' : 'Standard';
Integer priority = 1;— the case's priority level.String urgencyLabel = priority == 1 ? 'Urgent' : 'Standard';—priority == 1istrue, sourgencyLabelbecomes'Urgent'.
A short, single-value decision like labeling urgency is exactly where a ternary earns its keep — one line, no ceremony.
Trade-offs and when NOT to use this
Ternaries get hard to read fast once the condition or either branch is anything more than a short expression — and Apex doesn't allow nesting a switch inside one anyway. If you find yourself squinting at a ternary to understand it, that's the signal to rewrite it as a plain if/else instead. Prefer clarity over cleverness every time.
Exercise
Declare Integer age = 16. Using a ternary, declare a String ticketType that's 'Child' if age is under 18, otherwise 'Adult'. Debug it.
Show hint
age < 18 ? 'Child' : 'Adult'
The Ternary Operator Quiz
Leaderboard
- 1. Monde Masiza 2/2
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
The ternary operator (condition ? valueIfTrue : valueIfFalse) packs a simple if/else into a single expression — a nice shorthand for short, direct assignments, and a readability trap when overused.