Home › Learn › Java › Decisions and methods

if and else

Lesson 7 of 40. Run a block of code only when a condition holds.

if (condition) { ... } runs the block when the condition is true; else { ... } runs otherwise. The condition sits in parentheses and must be a boolean. Braces mark the block; Java lets you drop them for a single statement, but keeping them avoids a classic bug where a second line looks indented into the branch and is not.

The checks in this lesson change score before running main, so main has to work for any score, not just the one in the starter.

if (age >= 18) {
    System.out.println("adult");
} else {
    System.out.println("minor");
}

Your task

In main, print pass when score is 50 or more and fail otherwise. Then, on a second line, print perfect only when the score is exactly 100 (no line at all otherwise).

Hint 1

if (score >= 50) { System.out.println("pass"); } else { System.out.println("fail"); }

Hint 2

A second, separate if for the perfect line: if (score == 100) { ... } with no else.

Show the solution
public class Main {
    static int score = 72;

    public static void main(String[] args) {
        if (score >= 50) {
            System.out.println("pass");
        } else {
            System.out.println("fail");
        }
        if (score == 100) {
            System.out.println("perfect");
        }
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.