Home › Learn › Java › Decisions and methods

else if chains

Lesson 8 of 40. Pick one of several outcomes, in order.

if ... else if ... else tests conditions in order and runs the first block whose condition is true, then skips the rest. Order matters: for grade boundaries, test the highest first, because score >= 60 is also true for a 95.

Only one branch runs, so the last else is the catch-all for everything the earlier tests did not claim. When several conditions can all be true and you want all of their blocks to run, use separate if statements instead.

if (temp > 30) {
    label = "hot";
} else if (temp > 20) {
    label = "warm";
} else {
    label = "cold";
}

Your task

Set grade from score: A for 90 and above, B for 80 to 89, C for 70 to 79, D for 60 to 69, and F below that. Do it inside main, since the checks change score and run main each time.

Hint 1

if (score >= 90) { grade = "A"; } else if (score >= 80) { grade = "B"; } ... highest first.

Hint 2

The final else sets "F".

Show the solution
public class Main {
    static int score = 85;
    static String grade = "";

    public static void main(String[] args) {
        if (score >= 90) {
            grade = "A";
        } else if (score >= 80) {
            grade = "B";
        } else if (score >= 70) {
            grade = "C";
        } else if (score >= 60) {
            grade = "D";
        } else {
            grade = "F";
        }
        System.out.println(grade);
    }
}

    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.