Beginner 15 min read

If, Else If, and Else

By the end of this lesson, you'll be able to:

  • Chain multiple conditions with else if
  • Use a final else as a catch-all
  • Explain that only one branch in a chain ever runs

Prerequisites: "If Statements"

Chaining conditions

Integer leadScore = 65;

if (leadScore >= 80) {
    System.debug('Hot lead');
} else if (leadScore >= 50) {
    System.debug('Warm lead');
} else {
    System.debug('Cold lead');
}

Apex checks each condition top to bottom and runs the first one that's true — leadScore >= 50 matches here, so "Warm lead" prints, and nothing below it is even checked.

Only one branch ever runs

Even if a later condition in the chain would also be true, it's never evaluated once an earlier one matched. This is different from writing several separate if statements in a row, where every single one gets checked independently — a common source of subtle bugs when someone means "else if" but writes plain "if" instead.

A real business example: Insurance

Integer riskScore = 42;

if (riskScore >= 80) {
    System.debug('High risk — manual underwriting required');
} else if (riskScore >= 40) {
    System.debug('Medium risk — standard premium');
} else {
    System.debug('Low risk — discount premium');
}

Risk tiers are a textbook if/else if/else chain — a fixed number of ranges, checked in order, exactly one outcome selected.

Exercise

Declare Integer examScore = 74. Debug 'Distinction' for 90+, 'Pass' for 50-89, and 'Fail' for anything below 50, using if/else if/else.

Show hint

Check the highest threshold first — if (examScore >= 90) ... else if (examScore >= 50) ... else ...

APEX

If, Else If, and Else Quiz

1. In an if/else if/else chain, how many branches run?

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

else if lets you check several conditions in order, and a trailing else catches everything that didn't match any of them — together, these express "pick exactly one path" logic cleanly.