if / else if / else

The Course
•
4 min read

A condition is an expression that produces true or false. Numeric comparisons include <, <=, >, >=, == and !=. Use == to compare integer values; = assigns a new value. Read < as less than, <= as less than or equal to, > as greater than, >= as greater than or equal to, and != as not equal to. A boolean condition controls whether an if block runs.

An if/else chain selects one path. Java tests conditions from top to bottom and stops at the first true branch. Else is the fallback if none matched. Write braces even when a branch contains one statement, and indent its body four spaces. A statement after the whole chain runs regardless of which branch was chosen.

Thresholds need boundary cases

If a 60-minute plan is considered long, test 59, 60 and 61. Testing only 90 tells you nothing about accidentally using > instead of >=. Put more restrictive thresholds first when several can match the same value. Separate if statements have a different meaning: each asks its own question and more than one can run.

One category, with the largest threshold first Java
public class Main {
    public static void main(String[] args) {
        int minutes = 60;

        if (minutes >= 60) {
            System.out.println("Long");
        } else if (minutes >= 25) {
            System.out.println("Standard");
        } else {
            System.out.println("Short");
        }

        System.out.println("Plan checked");
    }
}
Check your prediction
Long
Plan checked

Sixty also meets the 25-minute threshold, but that branch is never reached after the first match. Move the smaller threshold first to observe the bug, then restore the intended order.

Two independent questions Java
public class Main {
    public static void main(String[] args) {
        int minutes = 60;

        if (minutes >= 25) {
            System.out.println("At least one standard session");
        }

        if (minutes >= 60) {
            System.out.println("Take a break too");
        }
    }
}
Check your prediction
At least one standard session
Take a break too

Both messages are useful, so two independent if statements are intentional. Do not replace every second if with else if without deciding whether the outcomes are exclusive.

Choose a singular label Java
public class Main {
    public static void main(String[] args) {
        int count = 1;
        String label;

        if (count == 1) {
            label = "session";
        } else {
            label = "sessions";
        }

        System.out.println(count + " " + label);
    }
}
Check your prediction
1 session

The declaration reserves a String variable, and every branch assigns it before use. Change count to 0 and 2. The wording is a decision you write; concatenation does not supply grammar automatically.

Your turn

Exercise

Choose a progress message

For completed=25 and goal=30, print Keep going. Print Goal reached when completed is at least goal, otherwise Keep going. Test completed=29, 30 and 31, and explain why two of those cases choose the same branch.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        int completed = 25;
        int goal = 30;
        // Choose one message.
    }
}
Hint 1: the idea

The completed amount reaching exactly the goal belongs to the successful branch.

Hint 2: a first step

Write one comparison that includes equality. The else branch covers every remaining case.

Show one solution
public class Main {
    public static void main(String[] args) {
        int completed = 25;
        int goal = 30;

        if (completed >= goal) {
            System.out.println("Goal reached");
        } else {
            System.out.println("Keep going");
        }
    }
}
Keep going

Change it and explain

Create three shipping bands using integer cents: orders at least 5000 ship free, at least 2000 pay 300, and smaller orders pay 700. Test just below and at both thresholds. Show that a 6000 order chooses only the free band. Then explain why that same order would match two separate if statements.

A condition can inspect a boolean variable directly, such as if (finished). There is no need to compare it with true. Keep the condition focused on the rule, and use a meaningful name for the value being checked.

Was this article helpful?

Your response is saved on this device.