Sub topic 3
Test Multiple Conditions in the Right Order
When a program has more than two choices, you can test several conditions in a row. A condition is a test that gives either true or false. An else-if chain is a series of these tests that starts with if. Each else if gives Java another test to try. A final else can handle what is left.
The key rule is simple: Java checks the tests from top to bottom and stops looking at the first true test. So the order is part of what your program means. For example, a score of 95 is both at least 70 and at least 90. If you want to give it the label “Excellent” rather than “Pass,” you need to put the test for “Excellent” first.
Build a chain for three results
Suppose you want a program to print one label for a quiz score:
- Scores of 90 or higher get “Excellent.”
- Scores from 70 through 89 get “Pass.”
- Scores below 70 get “Keep practicing.”
Save this program as ScoreBands.java. Run it the same way you ran your other Java programs. The int type holds whole numbers, and the operator >= means “greater than or equal to.” So score >= 90 asks whether the score is at least 90.
public class ScoreBands {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 70) {
System.out.println("Pass");
} else {
System.out.println("Keep practicing");
}
}
}This program prints “Pass.” To see why, trace it. To trace a program is to follow what it does one step at a time.
- Java tests whether 85 is at least 90. The result is false, so Java skips the first block. A block is a group of code inside braces.
- Java reaches else if and tests whether 85 is at least 70. The result is true, so Java runs that block and prints “Pass.”
- Java skips the final else block. It already chose a block in this chain.
Each block is a branch, or one path the program can take. You can add more else if branches between the first if and the final else. Each else if needs its own condition in parentheses. The final else does not have a condition. It runs only when all the tests above it were false.
Read each test with the earlier tests in mind
Look at score >= 70 on its own. It is true for 70, 85, 90, and 100. So why does the “Pass” branch cover only 70 through 89?
The second test is reached only after the first test fails. At that point, you already know the score is below 90. The second test adds one more fact: the score is at least 70. Put those facts together, and the score must be from 70 through 89. You do not have to test the upper end again.
The same idea helps you read the final else. Java reaches it only if the score was not at least 90 and was not at least 70. For these tests, that leaves scores below 70.
| Score | Is it at least 90? | Is it at least 70? | What prints? |
|---|---|---|---|
| 95 | True | Not checked | Excellent |
| 90 | True | Not checked | Excellent |
| 89 | False | True | Pass |
| 70 | False | True | Pass |
| 69 | False | False | Keep practicing |
Notice the difference between “false” and “not checked.” For 95, the second test would be true if Java checked it. But Java never reaches that test. When you trace a chain on paper, stop at the first true test. Do not mark the later tests as false.
See what goes wrong when the order changes
The next program uses the same tests, but it puts the test for 70 first. Predict what it will print for 95. Then save it as WrongOrder.java and run it to check your answer.
public class WrongOrder {
public static void main(String[] args) {
int score = 95;
if (score >= 70) {
System.out.println("Pass");
} else if (score >= 90) {
System.out.println("Excellent");
} else {
System.out.println("Keep practicing");
}
}
}It prints “Pass.” The first test is true, so Java skips the test for 90. Now imagine trying to reach “Excellent” with a different score. Any score of 90 or higher will also pass the test for 70. Any score that fails the test for 70 is too low to pass the test for 90. No whole-number score can reach the “Excellent” branch in this version.
Java still accepts the program. The code follows the rules for writing an else-if chain. It just does not follow your rules for quiz scores. Also, some inputs still give the right answer. If you test only 85 and 60, you might think the order is fine. A good test includes a score that could pass both tests, such as 95.
Do not replace the chain with separate tests
Two separate if statements do not follow the first-match rule. Each has its own test. If your program first uses if to print “Excellent” for scores at least 90, and then uses another if to print “Pass” for scores at least 70, a score of 95 prints both labels.
That can be useful when you want two actions to happen. But here the program should pick just one label. Keep the second test as else if so Java checks it only when the first test fails.
Order the tests by which result should win
Putting the larger number first worked for the quiz because both tests asked whether a score was at least a number. It is not a rule for every chain. The better rule is to ask which result should win when more than one test could be true.
Imagine a battery display that uses a whole number from 0 to 100. It should print “Charge now” at 5 percent or less. At 20 percent or less, it should print “Battery low,” unless it already chose “Charge now.” For all other levels, it should print “Battery OK.”
Here the smaller number comes first. The operator <= means “less than or equal to.”
public class BatteryStatus {
public static void main(String[] args) {
int battery = 4;
if (battery <= 5) {
System.out.println("Charge now");
} else if (battery <= 20) {
System.out.println("Battery low");
} else {
System.out.println("Battery OK");
}
}
}At 4 percent, both tests would be true if checked. “Charge now” wins because its test comes first. At 12 percent, the first test fails and the second passes. At 21 percent, both tests fail, so the program prints “Battery OK.” If you moved the test for 20 percent to the top, a battery at 4 percent would get the less urgent message.
A special case can work the same way. Suppose a quiz now gives “Perfect” for exactly 100. The operator == tests whether two values are equal. A check such as score == 100 must go before score >= 90, because 100 also passes the test for “Excellent.” If the exact check comes later, the program never gets to it for 100.
Tests can also cover groups that never overlap. For example, a score of exactly 100 and a score below 70 cannot both match the same score. For those two checks alone, either order gives the same result. Order matters most when the same input could pass more than one test.
Check the cutoffs and the leftover cases
A cutoff is a value where the result can change. In the quiz, 70 and 90 are cutoffs. A useful check is to try the number just below each cutoff, the cutoff itself, and the number just above it. This lets you see which side gets the cutoff value.
Go back to ScoreBands.java. Change only the value given to score, then run the program again. Write down what you expect before each run.
| Cutoff | Just below | At the cutoff | Just above |
|---|---|---|---|
| 70 | 69 prints “Keep practicing” | 70 prints “Pass” | 71 prints “Pass” |
| 90 | 89 prints “Pass” | 90 prints “Excellent” | 91 prints “Excellent” |
A common error is to write >, which means “greater than,” when you need >=. Try changing the first test to score > 90. A score of 91 still gets “Excellent” and 89 still gets “Pass.” But 90 now gets “Pass,” which is wrong for the quiz rules. If you test only the values beside the cutoff, you can miss the error. Put the >= test back when you are done.
Decide what else should mean
An else is not a check for valid input. It means “none of the earlier tests passed.” The score program does not check that a score is from 0 to 100. Given −1, it would print “Keep practicing.” Given 101, it would print “Excellent.” If the program should reject those scores, make that decision before it gives a quiz label. Do not expect the final else to catch both, since 101 already matches the first test.
You can leave off the final else when no match should mean no action. Java will skip the whole chain if every test fails. For the quiz, though, every score in the allowed range needs a label. The else branch makes sure low scores get one too.
Plan a chain before you type it
When a chain gets longer, start with the results you want, not the Java code. You can use this short process for a new set of rules:
- Write each result and the inputs that should get it. For the quiz, that includes “Pass” for 70 through 89, not just “Pass” for any score of at least 70.
- Pick a test for each branch. If one test also matches inputs meant for another branch, pick a value that matches both. Decide which result should win for that value and put its test first.
- Read the chain from top to bottom. For each branch, say what must already be false before Java can reach it. Check what the final else will get, or decide that you do not need one.
- Run one example for each result. Then run the values at and around the cutoffs. Include a value that could pass two tests, so you can check that the right branch wins.
For the quiz, 95 is a useful check for order, while 90 is a useful check for the operator. A score of 69 checks what happens when neither test passes. A few well-chosen scores tell you more about the chain than several scores that all take the same path.
Practice
Exercise
In ScoreBands.java, what prints for score 90? Does Java check whether the score is at least 70?
Show answer
It prints “Excellent.” The first test is true, so Java skips the test for 70.
Exercise
You add an else if for score == 100 just after the test for score >= 90. Why does the program never print “Perfect,” and how would you fix it?
Show answer
A score of 100 passes the test for 90 first. Put the exact check for 100 first and follow it with else if for score >= 90.
Exercise
In BatteryStatus.java, you change battery <= 5 to battery < 5, where < means “less than.” What prints at 5 percent, and why?
Show answer
It prints “Battery low.” Five is not less than 5, so the first test fails. Five is at most 20, so the second test passes.