AI Hints
Home›Java Tutorial›Comparison Operators, if, else and else if
Java · Lesson 30 of 120

else and else if

One path or another.

⏱ 2 min read▶ Video at 39:00🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Often, you want to do one thing when a condition is true, and something else when it's false. That's what else is for.

  • True: one thing
  • False: another
  • Exactly one runs

if and else

Can we pay? If the balance is at least the price, we accept. Else runs when the condition is false. Exactly one of the two blocks always runs. Run it. Forty isn't enough for fifty five. We need fifteen more.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int balance = 40;
        int price = 55;
        if (balance >= price) {
            System.out.println("Payment accepted.");
        } else {
            System.out.println("Not enough money.");
            System.out.println("You need " + (price - balance) + " more.");
        }
    }
}
Output
Not enough money.
You need 15 more.

A chain of choices

Else if adds more questions, checked one after another. Java checks each condition, top to bottom. The first true one wins, and the rest are skipped. The final else catches everything left over. The hour is fifteen. Run it. It's not less than twelve, but it is less than eighteen. Good afternoon.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int hour = 15;
        if (hour < 12) {
            System.out.println("Good morning");
        } else if (hour < 18) {
            System.out.println("Good afternoon");
        } else if (hour < 22) {
            System.out.println("Good evening");
        } else {
            System.out.println("Good night");
        }
    }
}
Output
Good afternoon

How Java decides

Java checks the first condition. If it's false, it moves to the next one. As soon as one is true, that block runs, and Java jumps past the rest. If none are true, the else block runs.

  1. hour < 12?
  2. hour < 18? ✓
  3. Run that block
  4. Skip the rest

Summary

Else runs when the if is false. Else if chains more checks, and the first true one wins. Next, combining conditions, with and, or, and not.

Key takeaways
  • if / else
  • else if chains
  • First true wins
Next up: Logical Operators — and, or, not