00:00

if-else Statement in Java – Explained with Examples

Last updated: 8 min read

Programs constantly make decisions: apply a discount or not, allow a login or reject it, choose a tax slab. In Java, the if statement and its partners else and else if are the basic tools for these decisions. They run a block of code only when a boolean condition is true.

This tutorial covers the simple if, if-else, the else-if ladder and nested if, with practical examples, cleaner alternatives and the mistakes that trip up beginners.

1. Forms of the if Statement

FormUse it when
ifYou want to run code only when a condition is true.
if-elseYou want to choose between two paths.
if-else-if ladderYou have several conditions to check in order.
Nested ifA decision depends on an earlier decision.

The condition inside the parentheses must be a boolean expression, usually built with relational and logical operators.

2. The Simple if Statement

Syntax
if (condition) {
    // runs only when condition is true
}
SimpleIf.java
public class SimpleIf {
    public static void main(String[] args) {
        double cartTotal = 1250.0;

        if (cartTotal >= 1000) {
            System.out.println("You get free delivery!");
        }

        int age = 15;
        if (age >= 18) {
            System.out.println("You can vote.");   // skipped: condition is false
        }
        System.out.println("Checks finished.");
    }
}
Output
You get free delivery!
Checks finished.

When the condition is false, Java simply skips the block and continues with the next statement.

3. The if-else Statement

Add else to run an alternative block when the condition is false. Exactly one of the two blocks runs.

Syntax
if (condition) {
    // runs when condition is true
} else {
    // runs when condition is false
}
IfElseDemo.java
public class IfElseDemo {
    public static void main(String[] args) {
        int balance = 800, withdrawal = 1200;

        if (balance >= withdrawal) {
            balance -= withdrawal;
            System.out.println("Withdrawal successful. Balance: " + balance);
        } else {
            System.out.println("Insufficient funds. Balance: " + balance);
        }

        int year = 2024;
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            System.out.println(year + " is a leap year");
        } else {
            System.out.println(year + " is not a leap year");
        }
    }
}
Output
Insufficient funds. Balance: 800
2024 is a leap year

4. The if-else-if Ladder

When there are more than two possibilities, chain conditions with else if. Java checks them from top to bottom and runs the block of the first true condition; the final else catches everything else. Order matters: put the most specific or smallest ranges first.

ElectricityBill.java
public class ElectricityBill {
    // if-else-if ladder: the first true condition wins
    static double bill(int units) {
        double amount;
        if (units <= 100) {
            amount = units * 3.0;
        } else if (units <= 200) {
            amount = 100 * 3.0 + (units - 100) * 4.5;
        } else if (units <= 400) {
            amount = 100 * 3.0 + 100 * 4.5 + (units - 200) * 6.0;
        } else {
            amount = 100 * 3.0 + 100 * 4.5 + 200 * 6.0 + (units - 400) * 7.5;
        }
        return amount;
    }

    public static void main(String[] args) {
        for (int units : new int[] {80, 150, 320, 500}) {
            System.out.printf("%3d units -> Rs. %.2f%n", units, bill(units));
        }
    }
}
Output
 80 units -> Rs. 240.00
150 units -> Rs. 525.00
320 units -> Rs. 1470.00
500 units -> Rs. 2700.00

Because the ladder stops at the first match, the condition units <= 200 does not need to repeat units > 100.

5. Nested if and Guard Clauses

An if inside another if is a nested if. It works, but deep nesting is hard to read. Guard clauses, which check for problem cases first and return early, keep the same logic flat:

NestedIf.java
public class NestedIf {
    static String login(String user, String password, boolean locked) {
        if (user.equals("asha")) {
            if (locked) {
                return "Account locked. Contact support.";
            } else if (password.equals("s3cret")) {
                return "Welcome, asha!";
            } else {
                return "Wrong password.";
            }
        } else {
            return "Unknown user.";
        }
    }

    // The same logic with guard clauses (early returns) is flatter and easier to read
    static String loginFlat(String user, String password, boolean locked) {
        if (!user.equals("asha")) return "Unknown user.";
        if (locked) return "Account locked. Contact support.";
        if (!password.equals("s3cret")) return "Wrong password.";
        return "Welcome, asha!";
    }

    public static void main(String[] args) {
        System.out.println(login("asha", "s3cret", false));
        System.out.println(login("asha", "oops", false));
        System.out.println(loginFlat("asha", "s3cret", true));
        System.out.println(loginFlat("ravi", "x", false));
    }
}
Output
Welcome, asha!
Wrong password.
Account locked. Contact support.
Unknown user.

6. Common Pitfalls and Modern Features

IfPitfalls.java
public class IfPitfalls {
    public static void main(String[] args) {
        int stock = 0;

        // Pitfall 1: a stray semicolon ends the if; the block always runs
        if (stock > 0); {
            System.out.println("Pitfall 1: this prints even though stock is 0");
        }

        // Pitfall 2: without braces, only the first statement belongs to the if
        if (stock > 0)
            System.out.println("in stock");
            System.out.println("Pitfall 2: this line is NOT part of the if");

        // Pitfall 3: compare strings with equals(), not ==
        String status = new String("ACTIVE");
        if (status == "ACTIVE") System.out.println("never printed");
        if (status.equals("ACTIVE")) System.out.println("Pitfall 3: equals() works");

        // Java 16+: pattern matching in an if condition
        Object value = 42;
        if (value instanceof Integer n && n > 40) {
            System.out.println("Pattern matching: " + n + " is a big Integer");
        }
    }
}
Output
Pitfall 1: this prints even though stock is 0
Pitfall 2: this line is NOT part of the if
Pitfall 3: equals() works
Pattern matching: 42 is a big Integer
  • Stray semicolon: if (stock > 0); has an empty body, so the following block always runs.
  • Missing braces: without { }, only the next single statement belongs to the if, whatever the indentation suggests. Always use braces.
  • Comparing strings with ==: use equals().
  • Pattern matching (Java 16+): if (value instanceof Integer n && n > 40) tests the type, casts and checks in one condition.

7. The Dangling else

In if (a) if (b) x(); else y();, the else belongs to the nearest if (the one testing b), not to the outer one. Braces remove all doubt about which if an else belongs to.

8. Alternatives to Long if-else Chains

  • Ternary operator for choosing between two values: String s = ok ? "Yes" : "No";. See Ternary Operator.
  • switch for comparing one value against many constants or patterns. See switch Statement.
  • Lookup maps (Map<String, Integer>) or TreeMap.floorEntry() for slabs and ranges.
  • Polymorphism: replace type-checking chains with overridden methods.

9. Best Practices

  • Always use braces, even for one-line bodies.
  • Keep conditions simple; extract complex ones into well-named variables or methods.
  • Prefer guard clauses over deep nesting.
  • Write if (isReady), not if (isReady == true).
  • Handle the "else" case deliberately; an unexpected value often deserves an error or log message.

10. Summary

  • if runs a block when a boolean condition is true.
  • if-else chooses between two blocks; the else-if ladder chooses the first true condition among many.
  • Nested ifs handle dependent decisions; guard clauses keep them readable.
  • Watch for stray semicolons, missing braces and == on strings.
  • Use the ternary operator, switch or maps when they express the logic more clearly.

Related Tutorials

Reference: dev.java: Control Flow Statements