Card 03/ 09

ExampleDifficulty: Beginner1 min

Conditionals Example: A Shipping Rate With switch

Three countries share one rate, written once, and the switch hands the value straight back.

A switch can turn a two-letter country code into a shipping rate, as the listing below does. It is the case switch fits best: one value compared against a fixed list of possible values, with no ranges involved.

java
String country = "DE";

double rate = switch (country) {
    case "UK" -> 2.99;
    case "IE", "FR", "DE" -> 6.49;
    default -> 14.99;
};

System.out.println(rate);
text
6.49

country is "DE", so the second case matches and the switch produces 6.49. Line 5 lists three codes separated by commas, so Ireland, France and Germany share one rate that is written once. default covers every code the list does not name.

This is the arrow form of switch, written with ->. In this form the whole switch can be an expression: it produces a value, and that value is assigned straight to rate.

A letter grade picked from a score by an if and else if ladder has the same structure: one value, tested in order, chooses one result. In both, one value decides, the branches are mutually exclusive (only one of them can run), and exactly one runs. What differs is the question: the grade asked whether the score fell inside a range, and the rate asks whether the code is exactly one of a few known values. That question is what decides between if and switch.