Sub topic 8
Choose if for Ranges or Predicates and switch for Discrete Cases
A parcel desk needs to make two decisions. First, it checks a parcel’s weight to choose a size label. Next, it checks the delivery option to decide what to print on the routing slip. Both decisions have several possible outcomes. But they ask different kinds of questions.
For the weight, the desk asks, “Is this number in a certain range?” For the delivery option, it asks, “Which of these exact names did the customer pick?” Use an if chain for the first question. A switch is a good fit for the second.
The key is to choose based on what the code needs to test, not on how many branches it has.
Read the Rule Before You Write the Code
Write the rule as a sentence first. Look for words such as “at most,” “between,” “and,” and “or.” They often point to conditions that fit an if. Look for phrases such as “one of these names” or “for each menu code.” They often point to exact matches that fit a switch.
A predicate is a test that gives true or false. “The parcel weighs more than 2,000 grams” is a predicate. So is “the counter is open and the customer has a receipt.” An if can test either one. The second test uses two facts, but the whole test still gives one true or false answer.
A discrete case is a separate, exact choice, such as the name “express” or the menu code 20. A switch compares a selector, the value you are choosing on, with case labels, the exact choices listed in the code. If your rule reads like a list of choices for one value, a switch can make that list easy to scan.
| Rule | Good starting choice | Why it fits |
|---|---|---|
| Give a discount for orders of at least 10 items. | if | The rule uses a cutoff, not a list of exact counts. |
| Allow pickup if the counter is open and the customer has a receipt. | if | The rule combines two facts in one test. |
| Show a different action for the names “pickup,” “standard,” and “express.” | switch | Each action depends on one exact delivery name. |
| Sound an alert only when the status is “offline.” | if | There is one short test and no list of actions to scan. |
Worked Example: Label and Route a Parcel
The desk stores weight as a whole number of grams. Its weight rules are:
- A weight of zero or less is invalid.
- From 1 to 500 grams, print “Light parcel.”
- From 501 to 2,000 grams, print “Regular parcel.”
- Above 2,000 grams, print “Heavy parcel.”
These are ranges. A range is a span of values covered by one rule. For example, 1 and 500 both get the same label, as does every whole number between them. The if chain can show the cutoffs directly. It does not need a separate branch for each possible weight.
The routing rules are different:
- For “pickup,” print “Hold at the counter.”
- For “standard,” print “Place in the standard bin.”
- For “express,” print “Place in the express bin.”
- For any other name, print “Check the delivery name.”
The names do not form a range. There is no useful question like “Is this name between pickup and express?” The program needs to match the exact text, so the routing rule fits a switch.
Run the Two Decisions Side by Side
Save this program as ParcelDesk.java. Use Java 14 or later for the arrow-style switch. Compile it with javac ParcelDesk.java, then run it with java ParcelDesk.
public class ParcelDesk {
public static void main(String[] args) {
int weightGrams = 500;
String deliveryOption = "express";
if (weightGrams <= 0) {
System.out.println("Invalid weight");
} else if (weightGrams <= 500) {
System.out.println("Light parcel");
} else if (weightGrams <= 2000) {
System.out.println("Regular parcel");
} else {
System.out.println("Heavy parcel");
}
switch (deliveryOption) {
case "pickup" -> System.out.println("Hold at the counter");
case "standard" -> System.out.println("Place in the standard bin");
case "express" -> System.out.println("Place in the express bin");
default -> System.out.println("Check the delivery name");
}
}
}The program prints “Light parcel” and then “Place in the express bin.” In the if chain, 500 is not invalid, but it is at most 500. In the switch, the text “express” matches the case with that name. Neither decision needs to know the result of the other.
Notice what each form makes easy to find. Suppose the desk raises the light parcel limit to 600 grams. You would look for the cutoff in the if chain. Suppose the desk adds a delivery option named “overnight.” You would look for the list of names in the switch. A good choice of branch makes the next change easier to spot.
Test the Cutoffs and the Exact Names
A boundary is a point where a rule changes its result. To check a boundary in a weight rule, try a value on each side of it. Change the weight in the program and keep the delivery option set to “express.” Save, compile, and run the program again after each change.
| Weight in grams | Expected first line | What the test checks |
|---|---|---|
| 0 | Invalid weight | Zero does not count as a parcel weight. |
| 1 | Light parcel | The first valid weight is light. |
| 500 | Light parcel | The light range includes its upper limit. |
| 501 | Regular parcel | The next gram starts the regular range. |
| 2,000 | Regular parcel | The regular range includes its upper limit. |
| 2,001 | Heavy parcel | The next gram starts the heavy range. |
Use 2000 and 2001 without commas when you type those numbers in Java.
Now set the weight back to 500 and change only the delivery option. Try “pickup,” then “Express” with a capital E, then “overnight.” The first line should stay the same each time. The second line should say “Hold at the counter” for “pickup” and “Check the delivery name” for the other two. The switch matches text exactly, so “Express” does not match “express.”
The two sets of tests follow the shape of the rules. For a range, focus on the points where the result changes. For a list of exact choices, try each listed choice and at least one unknown choice.
When Both Forms Can Work
An if can test an exact match. So finding an exact value in the rule does not mean you must use switch. If the only rule is “give a receipt when the menu code is 20,” one if test says all you need. A switch becomes more useful when there are several exact choices and each has its own action.
Compare these two ways to handle three menu codes. Both use the same code entered at a parcel kiosk. Save the program as ParcelKiosk.java, compile it with javac ParcelKiosk.java, and run it with java ParcelKiosk.
public class ParcelKiosk {
public static void main(String[] args) {
int menuCode = 20;
if (menuCode == 10) {
System.out.println("Weigh a parcel");
} else if (menuCode == 20) {
System.out.println("Print a receipt");
} else if (menuCode == 30) {
System.out.println("Call an attendant");
} else {
System.out.println("Unknown menu code");
}
switch (menuCode) {
case 10 -> System.out.println("Weigh a parcel");
case 20 -> System.out.println("Print a receipt");
case 30 -> System.out.println("Call an attendant");
default -> System.out.println("Unknown menu code");
}
}
}The program prints “Print a receipt” twice because it runs both versions for comparison. In a real program, you would keep only one.
In the if chain, you read the name menuCode three times. You also check that each test uses the same kind of comparison. In the switch, the name appears once, and the choices line up under it. That layout helps you see that the decision is about one value throughout. There is no set number of branches where you have to switch forms. Choose the version that makes the rule easier to read and change.
Now suppose the receipt rule changes: code 20 should print a receipt only if the printer has paper. There are two ways to look at the larger decision:
- If the menu code still picks the action, keep the switch. Check for paper inside the receipt branch. The case says what the user asked for. The if says whether the kiosk can do it.
- If the whole decision is simply “Should I print a receipt now?”, use an if that checks both the code and the paper. There is no need to list actions that this part of the program does not handle.
The same facts can appear in both designs. What matters is the question this part of the code needs to answer.
Common Mistakes When Choosing a Branch
Treating Every Number as a Range
Menu codes are numbers, but they act like names. Code 20 means “print a receipt” because the kiosk rules say so. Code 21 does not mean almost the same thing. By contrast, 501 grams really is one gram more than 500 grams, and that difference matters at a cutoff.
Ask what the number means before choosing a form. Counts and measurements often have cutoffs. Menu codes and other fixed labels often need exact matches.
Making Up Codes Just to Use switch
You could give each weight range a code, then switch on that code to print a label. But first you would still need to work out which range the weight belongs to. If the only goal is to print that label, the extra codes make the rule harder to follow. A reader has to look in one place for the cutoffs and another for the labels.
A named group can be useful when the program needs it for several jobs, such as printing a label and setting a fee. But if you only need it to make a switch possible, keep the direct if chain.
Mixing Up a Named Option and a Rule About That Option
“Express” is an exact delivery option. “Light enough for express” is a test about weight. If the desk offers express only for parcels up to 2,000 grams, a match on “express” alone does not check that limit.
Name both facts in plain words: “The customer chose express” and “the parcel weighs at most 2,000 grams.” Then decide whether you are routing all delivery options or answering just one yes-or-no question about express. This keeps the weight rule from getting lost in the list of names.
Leaving Unknown Choices Unclear
If an app gets a delivery name it does not know, should it show an error, ask again, or do nothing? That is part of the rule. In the parcel program, the default branch makes the answer clear: print “Check the delivery name.” It does not quietly send the parcel to the standard bin.
Likewise, an else is only a good fallback when it means what you intend. In the weight chain, “Heavy parcel” is a good fallback because the earlier tests already handle invalid, light, and regular weights. An else that said “Heavy parcel” without any check for invalid weights would not show the full rule.
Make the Choice in Three Steps
- Say what the decision asks. Is it “Does this test pass?” or “Which exact choice did we get?”
- Pick the form that shows the rule directly. Use if for ranges and tests that combine facts. Consider switch when several branches match exact choices for one value.
- Check the cases that are easy to miss. Try each side of a cutoff, an exact choice, and an unknown choice where those tests apply.
The examples here use statements, which tell Java to do something, such as print a line. If your job is to compute a value for later use, Java also has a switch expression. An expression is code that produces a value. The same question about the rule still comes first: are you testing conditions or matching a list of exact choices?
Practice
Exercise
A ticket desk charges one rate for ages under 12, another for ages 12 through 64, and a third for ages 65 and up. Which branch form fits, and what ages would you test at the cutoffs?
Show answer
Use an if chain because the rates depend on ranges. Test ages 11 and 12 at the first cutoff and ages 64 and 65 at the second.
Exercise
A kiosk accepts the exact commands “map,” “hours,” and “help.” It should show “Unknown command” for anything else. Which form would you pick, and what would you test besides the three known commands?
Show answer
Use a switch on the command with a default for unknown names. Try an unlisted command such as “exit.” Try “Map” too if you need to check that only the exact spelling “map” matches.
Exercise
The parcel desk will accept express only when the weight is valid and at most 2,000 grams. If the code only needs to answer “Can we accept this express parcel?”, what should it use?
Show answer
Use an if with a test that checks both weight limits: the weight must be greater than zero and at most 2,000 grams. If the code has not already checked the delivery option, include a check that the option is “express.”