← Java from Scratch Lesson 14 of 88 · 10 XP

if / else

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

if (hp <= 0) {
    System.out.println("Game over");
} else if (hp < 30) {
    System.out.println("Careful!");
} else {
    System.out.println("All good");
}

String label = hp > 0 ? "alive" : "dead";    // the ternary operator

The branches are checked from top to bottom, and the first one that fits runs. The curly braces can be left out if a branch has one statement — but braces are safer: a second line added later won't "fall out" of the if.

Task. For a score of 0–100, print the grade: 90+ → A, 75–89 → B, 60–74 → C, below that → F.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.