Lesson 2 of 514 minModule progress 0%

Module 4: Decision Making

`if` and `else`

Run one block when a condition is true and another block when it is false.

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 a basic `if` statement
  • Add an `else` block for the fallback case
  • Match conditions to simple everyday program rules

The if block: Java runs the code inside an if block only when the condition is true.

The else block: Use else for the fallback path when the if condition is false.

Why this matters: Once your program can choose between two paths, it starts behaving more like a real tool and less like a fixed script.

Keep branches small: In beginner code, short branches are easier to test and understand.

Runnable examples

Simple `if` / `else`

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

        if (age >= 18) {
            System.out.println("Adult");
        } else {
            System.out.println("Not an adult");
        }
    }
}

Expected output

Not an adult

Check a boolean variable

public class Main {
    public static void main(String[] args) {
        boolean hasTicket = true;

        if (hasTicket) {
            System.out.println("Entry allowed");
        } else {
            System.out.println("Entry denied");
        }
    }
}

Expected output

Entry allowed

Common mistakes

Adding a semicolon right after the `if` condition

Write `if (condition) { ... }` without a semicolon after the closing parenthesis.

Mini exercise

Write an `if` / `else` that prints `Pass` when a score is at least 50 and `Try again` otherwise.

Summary

  • `if` handles the true case.
  • `else` handles the fallback case.

Next step

If two branches are not enough, chain multiple checks with `else if`.

Sources used

Advertisement

Lesson check

When does the `else` block run?

Next lesson →