Skip to content
KALANBLON
Show contents

Chapter 1 of 6 · 20 min

if, else and switch

By the end of this chapter, you'll be able to

  • Write a condition with if, else if and else
  • Combine conditions with &&, || and !
  • Use the switch expression with arrows
  • Compare two texts with equals rather than ==

if, else if, else

void main() {
    int battery = 35;
    boolean subscriber = true;

    if (battery >= 80) {
        IO.println("No need to charge");
    } else if (battery >= 20 && subscriber) {
        IO.println("Normal charge, subscriber rate");
    } else if (battery >= 20) {
        IO.println("Normal charge");
    } else {
        IO.println("Priority fast charge");
    }
}
Normal charge, subscriber rate
  • The condition is written between parentheses and must be of type boolean. Unlike in C, a number isn't accepted as a condition: if (battery) doesn't compile.
  • The conditions are tested from top to bottom; only the first true block runs.
  • Comparisons: ==, !=, <, <=, >, >=. Combinations: && (and), || (or), ! (not). Java stops as soon as the result is known: in a && b, if a is false, b isn't evaluated.

The switch expression

To choose between exact values, Java offers a modern switch, with arrows. It can even produce a value:

void main() {
    String day = "saturday";
    String hours = switch (day) {
        case "saturday" -> "9 am - 1 pm";
        case "sunday" -> "Closed";
        default -> "8 am - 6 pm";
    };
    IO.println("Opening hours on " + day + ": " + hours);

    int rating = 3;
    switch (rating) {
        case 1, 2 -> IO.println("Needs work");
        case 3 -> IO.println("Good");
        case 4, 5 -> IO.println("Excellent");
        default -> IO.println("Invalid rating");
    }
}
Opening hours on saturday: 9 am - 1 pm
Good
  • With arrows ->, each case is independent: no break to write, and no risk of "falling through" into the next case.
  • Several values can share a case: case 1, 2 ->.
  • switch works with integers, characters, texts (String) and enumerations.
  • When the switch produces a value, the compiler checks that every case is covered. With a text or a number, you can't list every possible value: so default is mandatory.

We display the fare.

Step 7 of 7
Text description of the animation
  1. Reduced fare for seniors and for students under 26.
  2. age is 67.
  3. This isn't a student.
  4. Left-hand side of the ||: true.
  5. With ||, one true side is enough: the right-hand side isn't even evaluated.
  6. The ternary operator picks 150 because the condition is true.
  7. We display the fare.

condition ? valueIfTrue : valueIfFalse is the ternary operator: a compact if/else that produces a value.

Your turn

Worked exercise

Worked exercise: the shipping price

A parcel service charges by destination and weight: "domestic" costs €5 up to 2 kg, then €9; "europe" costs €12; "world" costs €25; any other destination is refused. Parcels over 30 kg are always refused. Write the program for a given destination and weight, and display the price. For "domestic" and 3.5 kg, it must display Price: 9 €.

Hint 1
First handle the general refusal: if (weight > 30).
Hint 2
Then a switch expression on the destination produces the price. For "domestic", use the ternary operator on the weight. For an unknown destination, return for example -1.
Show the solution and common mistakes
void main() {
    String destination = "domestic";
    double weight = 3.5;

    if (weight > 30) {
        IO.println("Parcel refused: too heavy");
        return;
    }
    int price = switch (destination) {
        case "domestic" -> weight <= 2 ? 5 : 9;
        case "europe" -> 12;
        case "world" -> 25;
        default -> -1;
    };
    if (price < 0) {
        IO.println("Unknown destination: " + destination);
    } else {
        IO.println("Price: " + price + " €");
    }
}
Price: 9 €

return; ends main immediately: the rest isn't run.

Common mistakes:

  • Writing if (destination == "domestic"): with a text typed on the keyboard, this test would be false. A switch on a String, on the other hand, compares contents correctly.
  • Forgetting the default: the compiler refuses a switch that produces a value without covering every case.

Summary

  1. 1if (condition) { … } else if (…) { … } else { … }: the condition must be a boolean.
  2. 2&&, || and ! combine conditions, evaluated from left to right with short-circuiting.
  3. 3The switch expression with -> needs no break and can produce a value.
  4. 4condition ? a : b chooses between two values.
  5. 5Always compare Strings with equals, never with ==.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.