Card 02/ 09
Conditionals Example: A Letter Grade With if and else if
A score of 74 matches two conditions, and the order of the rungs decides which one wins.
An if ladder can turn a test score out of 100 into a letter grade, as the listing below does. It shows the rule that decides what happens when more than one condition is true: Java tries the conditions from top to bottom and runs only the first one that matches.
int score = 74;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 70) {
grade = "B";
} else if (score >= 50) {
grade = "C";
} else {
grade = "fail";
}
System.out.println(grade);BThe score is 74. It fails the first condition (score >= 90) and passes the second (score >= 70), so grade becomes "B". It would also pass the third condition, score >= 50, but that rung is never tried. else if means "try this only if every condition above was false", so once one branch has run, the rest of the ladder is skipped.
What makes this an if problem is that each grade covers a range of scores rather than one exact value. Only a condition can express a range, which is why the ladder is the right shape here.
← → move through sections and cards