← Chapter 4 — Decision Making & Loops

16. if, else if & else

mixed

Description

An if statement runs a block only when its condition is true. Add else if branches for additional conditions and else for the remaining case.

Conditions should express a real rule in plain language. Indentation and braces make each possible path easy to inspect.

Subtopics

Simple decision

Description

if guards a block of code.

Explanation

The body runs only for true conditions.

Example

if (score >= 40) { System.out.println("Passed"); }

Multiple branches

Description

else if checks another condition.

Explanation

Branches are tested from top to bottom.

Example

if (score >= 90) { grade = 'A'; } else { grade = 'B'; }

Explanation

Order matters. Put the most specific or highest threshold first; otherwise an earlier broad condition can make a later branch unreachable.

Example

public class GradeDecision {
    public static void main(String[] args) {
        int score = 84;
        if (score >= 90) System.out.println("A");
        else if (score >= 75) System.out.println("B");
        else System.out.println("Keep practicing");
    }
}

Key points

  • if runs for a true condition.
  • Branches are checked in order.
  • Use braces for maintainable code.

Video

Open video

Open reference