Card 01/ 09
All 9 cards
ConceptDifficulty: Beginner1 min
Making the Program Take One Path and Not the Other
A program that runs its lines from top to bottom can do exactly one thing. The moment you want it to charge a different delivery fee for a different country, it needs a way to leave lines out.
Java gives you two shapes for that, and the difference between them is what they test.
if (weight > 20) {
fee = 9.99;
} else if (weight > 5) {
fee = 4.99;
} else {
fee = 2.99;
}switch (country) {
case "UK" -> fee = 2.99;
case "IE" -> fee = 4.99;
default -> fee = 9.99;
}An if ladder evaluates a condition at each step, and the conditions can be anything — ranges, comparisons, method calls, combinations. A switch takes one value and looks for a matching constant, which is a narrower question and a clearer one when it is the question you have.
Both leave lines out, and that is the whole idea: a branch is a way of writing more code than will ever run in one pass. Which shape you pick decides how obvious it is to the next reader what the decision was actually about.