Sub topic 8
Choose if for Ranges or Predicates and switch for Discrete Cases
A branch is a path that a program can take. In Java, both if and switch can pick a branch. To choose between them, ask what kind of question your code needs to answer.
Use if when the question sounds like “Is the parcel heavy?” or “Is the parcel heavy or fragile?” A predicate is a test that gives a true or false answer. A range is a span of values, such as all weights from 1,000 grams up to but not including 5,000 grams. An if test can check a range or combine facts about the parcel.
Use switch when the question sounds like “Which exact service code did the customer pick?” The selector is the value that switch checks. Each case names an exact choice, such as “standard,” “express,” or “pickup.” These are discrete choices: separate options, not a span of values.
Read the rule before choosing the code
Look at the rule you need to write, not just the type of the input. A number can stand for an exact menu choice, so switch can fit. A number can also be a weight you compare with a limit, so if can fit. The same type of data can lead to a different choice.
You can use an if chain for exact choices too. But when each test checks the same value against a different label, switch puts that value in one place. A reader can see what all the cases have in common. If there is only one check, such as “Did the customer choose pickup?”, an if is often easier to read.
Worked example: Send a parcel to the right place
A shipping desk makes two decisions for each parcel:
- Pick a handling area using the parcel’s weight and whether it is fragile. Send heavy or fragile parcels to the special desk. Of the parcels left, send those that weigh at least 1,000 grams to the regular belt. Put lighter ones in the small bin.
- Print a routing message for the exact service code. Print an error message if the code is not known.
The first decision uses if because it checks limits and can use two facts at once. The second uses switch because it matches one input against a list of codes.
Save this program as ParcelDesk.java. With Java 14 or later, compile it with javac ParcelDesk.java and run it with java ParcelDesk.
public class ParcelDesk {
public static void main(String[] args) {
int weightGrams = 1200;
boolean fragile = false;
String service = "express";
if (weightGrams >= 5000 || fragile) {
System.out.println("Use the special handling desk.");
} else if (weightGrams >= 1000) {
System.out.println("Use the regular parcel belt.");
} else {
System.out.println("Use the small parcel bin.");
}
switch (service) {
case "standard" -> System.out.println("Route to standard shipping.");
case "express" -> System.out.println("Route to express shipping.");
case "pickup" -> System.out.println("Hold for pickup.");
default -> System.out.println("Unknown service code.");
}
}
}Trace the two decisions
The symbol pair || means “or.” The first test passes if the parcel weighs at least 5,000 grams or is fragile. Here, neither is true. The next test passes because 1,200 is at least 1,000. The program prints “Use the regular parcel belt.”
Then switch checks the service code. It matches “express,” so the program prints “Route to express shipping.” The parcel’s weight did not help pick this message. Likewise, the service code did not help pick the handling area. The program needs both answers, so it runs both decisions.
Change one input at a time
Start each row from the original program. Before you run it, predict which message will change and which will stay the same.
| Change | Handling message | Routing message |
|---|---|---|
| Set the weight to 5,000 grams. | Use the special handling desk. | Route to express shipping. |
| Set fragile to true. | Use the special handling desk. | Route to express shipping. |
| Set the service code to “Express.” | Use the regular parcel belt. | Unknown service code. |
The exact limit of 5,000 grams belongs at the special desk because the test says “at least.” The capital E in “Express” matters too: it does not match the lowercase case label.
Check whether a new rule changes your choice
Suppose the desk adds an “overnight” service. That is another exact code, so it fits as a new switch case. Now suppose the desk wants to flag any parcel that is both fragile and booked for pickup. That rule joins two facts, so an if test fits. If the check only matters for pickup, it can go inside the pickup case. You do not need to replace the whole switch.
Practice
Exercise
A notice is sent at 30 days overdue or later. A separate rule picks a contact method from “email,” “text,” and “mail.” Which construct fits each rule?
Show answer
Use if for the overdue rule because it tests a range. Use switch for the contact method because one value can match one of several exact labels.