← Retour au cours: Java from scratch

Conditionals: if, else and modern switch

Vidéo bientôt disponible

So far your programs ran the instructions one after another, from top to bottom. Real programs make decisions: if the password is correct you get in, otherwise an error is shown; if the order exceeds a certain amount, shipping is free. Conditional structures let the program choose which path to follow depending on the value of a condition, which is always a boolean expression.

if, else if and else

The basic form is if (condition) { ... }. The block between braces runs only if the condition is true. With else you add the alternative path and with else if you chain several conditions: Java evaluates them in order and runs only the first block whose test is true. That is why order matters: put the most specific conditions first. Although Java lets you omit the braces when the block has a single statement, it is better to always include them; they prevent mistakes when you later add a second line.

java
public class Main {
    public static void main(String[] args) {
        int score = 72;

        if (score >= 90) {
            System.out.println("Excellent");
        } else if (score >= 70) {
            System.out.println("Good");      // this one runs
        } else if (score >= 50) {
            System.out.println("Pass");
        } else {
            System.out.println("Fail");
        }

        // Combining conditions
        int age = 16;
        boolean hasPermission = true;
        if (age >= 18 || (age >= 14 && hasPermission)) {
            System.out.println("Access granted");
        }

        // Ternary operator: a compact if/else that produces a value
        String label = score >= 50 ? "approved" : "failed";
        System.out.println(label);

        // Classic bug: = instead of == does not compile with int
        // if (score = 50) { }   // error: int cannot be converted to boolean
    }
}

The ternary operator condition ? valueIfTrue : valueIfFalse is a short way to choose between two values. Use it for simple cases; if the expression becomes hard to read, go back to a normal if. A Java detail: if you write if (x = 5) with an int, the compiler warns you with an error, because the condition must be boolean. In other languages that slip goes unnoticed.

switch: the classic and the modern style

When you compare the same variable with many values, switch is clearer than a chain of else if. The classic style uses case with a colon and requires a break at the end of each case; if you forget it, execution continues into the next case (fall-through), a very typical mistake. Since Java 14 there is the modern form with arrows: each case uses -> and needs no break. In addition, switch can be an expression that returns a value, and the compiler forces you to cover every possible case with a default.

java
public class Main {
    public static void main(String[] args) {
        int day = 6;

        // Switch expression: returns a value, no break needed
        String type = switch (day) {
            case 1, 2, 3, 4, 5 -> "weekday";
            case 6, 7 -> "weekend";
            default -> "invalid day";
        };
        System.out.println(type);   // weekend

        // Arrow cases can run several statements and use yield
        String command = "stop";
        int code = switch (command) {
            case "start" -> 1;
            case "stop" -> {
                System.out.println("Stopping...");
                yield 2;
            }
            default -> -1;
        };
        System.out.println(code);   // 2

        // Classic style: break is required
        switch (day) {
            case 6:
                System.out.println("Saturday");
            case 7:
                System.out.println("Sunday (fall-through!)");
                break;
            default:
                System.out.println("other");
        }
    }
}

Common mistakes

  • Putting a semicolon right after the if: if (x > 0); { ... } makes the block always run.
  • Comparing Strings with == inside an if; in a switch Java uses equals for you, but in an if you must write it yourself.
  • Forgetting the break in a classic switch and getting fall-through.
  • Writing 18 <= age <= 65: you must split it into two comparisons with &&.
  • Nesting too many ifs: if you go past three levels, extract the logic or use combined conditions.

Testez vos acquis

Question 1 sur 1

What happens if you forget break in a classic switch?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →