Card 01/ 09
Conditionals in Java: if and switch
They let one method charge a different delivery fee for each weight and each country.
A conditional is a statement that decides which lines of a program run, based on a value the program only knows while it is running. Java has two: the if statement, which tests any condition that is true or false, and the switch statement, which compares one value against a list of fixed values.
Without a conditional, a program does the same thing for every input. A shop that charges for delivery needs more than that: a heavier parcel costs more, and a parcel to Ireland costs more than one sent within the UK. The fee depends on data, so the code has to choose.
if (weight > 20) {
fee = 9.99;
} else if (weight > 5) {
fee = 4.99;
} else {
fee = 2.99;
}An if statement evaluates a condition, which is any expression that produces true or false, such as weight > 20. When it is true, the block in braces runs. else if adds another condition that is tried only when every condition above it was false, and else catches whatever is left. A chain like this is usually called an if ladder, and each condition is one rung.
switch (country) {
case "UK" -> fee = 2.99;
case "IE" -> fee = 4.99;
default -> fee = 9.99;
}A switch takes a single value, here the country code, and compares it with each case in turn. The case that matches runs, and default runs when none does. The -> arrow is the modern way to write a case (Java 14 and later). A switch cannot ask "is the weight more than 20?"; it can only ask "is the value exactly this?".
Both statements do the same job: they let a program hold code for several situations and run only the part that fits the current one. What differs is the question each one asks. if asks whether a condition is true, and switch asks which of several known values it has been given.
So the first thing to decide when you write a choice is what you are testing: a condition calls for if, and one value compared against fixed values calls for switch.
← → move through sections and cards