A plain if statement runs code only when its condition is true. But often you also want to do something when the condition is false, or choose between several possibilities. That is what else and else if are for.
Add an else block to run code when the if condition is false. Exactly one of the two blocks runs:
Integer score = 55;
if (score >= 60) {
System.debug('You passed.');
} else {
System.debug('You did not pass.');
}
When there are more than two outcomes, chain conditions with else if. Apex checks each condition in order from top to bottom and runs the block for the FIRST one that is true. Once a match is found, the rest are skipped:
Integer score = 82;
if (score >= 90) {
System.debug('Grade: A');
} else if (score >= 80) {
System.debug('Grade: B'); // this runs
} else if (score >= 70) {
System.debug('Grade: C');
} else {
System.debug('Grade: F');
}
Because the first true condition wins, put the most specific or highest conditions first. If you checked score >= 70 before score >= 90, every high score would match the 70 branch and the 90 branch could never run.
The trailing else catches everything that did not match any earlier condition. You can leave it off if there is nothing to do in that case, but it is a good habit for handling the leftover situations.
An if / else if / else chain lets your code pick exactly one path out of many.