Unit 04 · lesson
Branch Order Changes Which Rule Wins
Conditions often overlap. In an if / else if / else chain, the first matching branch wins.
Consider grade bands:
if (score >= 70) {
IO.println("passing");
} else if (score >= 90) {
IO.println("excellent");
}
What happens for 95?
The first condition is already true, so Java prints passing. The >= 90 branch is never reached.
The syntax is valid. The branch order violates the intended priority.
A corrected ordering:
if (score >= 90) {
IO.println("excellent");
} else if (score >= 70) {
IO.println("passing");
} else {
IO.println("not yet passing");
}
Independent rules are different
Suppose a diagnostic report needs to print every condition that applies:
if (batteryLow) {
IO.println("LOW BATTERY");
}
if (sensorFault) {
IO.println("SENSOR FAULT");
}
If both are true, both messages appear.
Changing this into if / else if would hide the second fault whenever the first is true.
Ask:
Are these choices mutually exclusive, or can more than one be true at the same time?
That question should determine the structure.
Put invalid data before category logic
Imagine classifying a percentage:
if (percent >= 90) {
IO.println("high");
} else if (percent >= 70) {
IO.println("medium");
} else {
IO.println("low");
}
What does -15 produce? low.
But perhaps -15 is not a legitimate percentage at all.
A stronger decision tree validates the domain first:
if (percent < 0 || percent > 100) {
IO.println("INVALID");
} else if (percent >= 90) {
IO.println("high");
} else if (percent >= 70) {
IO.println("medium");
} else {
IO.println("low");
}
Now an impossible input cannot masquerade as a legitimate low score.
Draw the branch tree
Before coding, draw this requirement:
A temperature reading from -40 through 125 is valid. Valid values above 80 are HOT, values below 0 are COLD, and all other valid values are NORMAL.
Your tree should make validation the first boundary.
Then create test cases that hit:
- below valid range;
- exactly -40;
- exactly 0;
- exactly 80;
- 81;
- exactly 125;
- above valid range.
Those are not random examples. They expose boundaries where comparison operators and branch order matter.
Switch when the decision is about one value
Later Java offers switch expressions that can make discrete choices readable. For example:
String command = "start";
String message = switch (command) {
case "start" -> "system starting";
case "stop" -> "system stopping";
case "status" -> "system ready";
default -> "unknown command";
};
IO.println(message);
Do not replace every if with switch. Use the structure that exposes the actual decision.
Evidence
Submit one branching problem with:
- the prose requirement;
- a decision tree;
- at least five boundary-focused cases;
- the Java implementation;
- one deliberately bad branch ordering and the input that exposes it;
- the corrected ordering.
You are proving that structure came from the decision model, not from whichever syntax you remembered first.