Lesson 3 of 514 minModule progress 0%

Module 4: Decision Making

`else if` Chains

Check more than two possible cases in a clear top-to-bottom order.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-16

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, edited by hand, and checked against current Java 25 documentation and runnable examples.

Learning goals

  • Write an `if` / `else if` / `else` chain
  • Order conditions from most specific to least specific when needed
  • Use chained logic for simple grading or categorization programs

Why this matters: Many beginner programs need more than a yes/no answer. Grades, menu categories, and age brackets all need multiple branches.

How the chain works: Java tests each condition in order and runs the first matching block. After one match, the rest of the chain is skipped.

Order matters: Put more specific or higher-priority conditions earlier when conditions could overlap.

Keep the chain readable: If the conditions become too many or too repetitive, that is a sign to simplify your logic or use a switch in some cases.

Runnable examples

Grade bands

public class Main {
    public static void main(String[] args) {
        int score = 83;

        if (score >= 90) {
            System.out.println("A");
        } else if (score >= 80) {
            System.out.println("B");
        } else if (score >= 70) {
            System.out.println("C");
        } else {
            System.out.println("Below C");
        }
    }
}

Expected output

B

Temperature categories

public class Main {
    public static void main(String[] args) {
        int temperature = 28;

        if (temperature >= 35) {
            System.out.println("Hot");
        } else if (temperature >= 20) {
            System.out.println("Warm");
        } else {
            System.out.println("Cool");
        }
    }
}

Expected output

Warm

Common mistakes

Putting a broader condition before a narrower one

Order your checks so earlier conditions do not accidentally catch later cases.

Mini exercise

Write an `else if` chain that prints a letter grade for a score from 0 to 100.

Summary

  • `else if` lets you check multiple cases.
  • Only the first matching branch runs.

Next step

Some multi-branch checks are clearer with `switch` instead of a long chain.

Sources used

Advertisement

Lesson check

What happens after one `else if` branch matches?

Next lesson →