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');
}
Integer leadScore = 65;— the score being classified.- (blank line)
if (leadScore >= 80) {—false(65 is not ≥ 80), so Apex moves on to check the next condition.System.debug('Hot lead');— skipped.} else if (leadScore >= 50) {—true— this is the first matching condition.System.debug('Warm lead');— runs, because line 5 matched.} else {— the final catch-all — never reached, since line 5 already matched.System.debug('Cold lead');— skipped.}— closes the whole chain.
Apex checks each condition top to bottom and runs the first one that's true — nothing below it is even checked once a match is found.
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');
}
Integer riskScore = 42;— the score being classified.- (blank line)
if (riskScore >= 80) {—false.System.debug('High risk — manual underwriting required');— skipped.} else if (riskScore >= 40) {—true— the first matching condition.System.debug('Medium risk — standard premium');— runs.} else {— never reached.System.debug('Low risk — discount premium');— skipped.}— closes the chain.
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 ...
If, Else If, and Else Quiz
Leaderboard
- 1. Monde Masiza 1/1
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.