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';
  1. Integer stock = 3; — the quantity on hand.
  2. String stockLabel = stock > 0 ? 'In Stock' : 'Out of Stock'; — read the ? : part as "if stock > 0, use 'In Stock'; otherwise use 'Out of Stock'." Since 3 > 0 is true, stockLabel becomes 'In Stock'.

This is functionally identical to:

String stockLabel;
if (stock > 0) {
    stockLabel = 'In Stock';
} else {
    stockLabel = 'Out of Stock';
}
  1. String stockLabel; — declared, not yet assigned.
  2. if (stock > 0) { — true.
  3. stockLabel = 'In Stock'; — runs, assigning the value.
  4. } else { — never reached.
  5. stockLabel = 'Out of Stock'; — skipped.
  6. } — closes the if/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';
  1. Integer priority = 1; — the case's priority level.
  2. String urgencyLabel = priority == 1 ? 'Urgent' : 'Standard'; — priority == 1 is true, so urgencyLabel becomes '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'

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

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.

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.