Beginner 15 min read

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';

Read it as: "if stock > 0, use 'In Stock'; otherwise use 'Out of Stock'." This is functionally identical to:

String stockLabel;
if (stock > 0) {
    stockLabel = 'In Stock';
} else {
    stockLabel = 'Out of Stock';
}

— just four lines shorter, for exactly this simple case.

A real business example: Case Management

Integer priority = 1;
String urgencyLabel = priority == 1 ? 'Urgent' : 'Standard';

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'

APEX

The Ternary Operator Quiz

1. What does condition ? a : b evaluate to?

2. A deeply nested ternary is usually more readable than an equivalent if/else if chain.

Log in to submit the quiz and save your score.

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.