Java for Beginners, Lesson 16: if, if-else and else-if Ladder in Java

Java for Beginners · Module 4: Control Flow


🎯 Making Decisions

So far every program ran line after line, in order. Real programs need to choose: if the marks are 40 or more, print “Pass”; otherwise print “Fail”. Java makes decisions with the if statement, which uses the true/false conditions you built in Lesson 13.

📌 An if statement runs a block of code only when its condition is true. else gives an alternative, and else if lets you test several conditions in order.

1️⃣ The Simple if

Condition
marks >= 40 ?
true ➜
Run the if-block
Condition
marks >= 40 ?
false ➜
Skip the block
carry on after it

Figure 1: A simple if: the block runs only when the condition is true.

Syntax: if (condition) { statements }. The condition must be in brackets and must be a boolean.

public class IfDemo {
    public static void main(String[] args) {
        int marks = 56;
        if (marks >= 40) {
            System.out.println("You passed.");
        }
        System.out.println("Done.");
    }
}
🖥️ Output:
You passed.
Done.
  • The condition marks >= 40 is true, so the block runs.
  • Done. is outside the braces, so it prints no matter what.
  • Always use braces { }, even for one statement. It avoids bugs when you add lines later.

2️⃣ if – else

Use else when you need exactly one of two outcomes.

public class IfElseDemo {
    public static void main(String[] args) {
        int number = 17;
        if (number % 2 == 0) {
            System.out.println(number + " is even");
        } else {
            System.out.println(number + " is odd");
        }

        int age = 16;
        if (age >= 18) {
            System.out.println("Can vote");
        } else {
            System.out.println("Cannot vote yet, wait " + (18 - age) + " years");
        }
    }
}
🖥️ Output:
17 is odd
Cannot vote yet, wait 2 years
  • Exactly one of the two blocks runs, never both and never neither.
  • The even/odd test uses % from Lesson 12: an even number leaves remainder 0 when divided by 2.

3️⃣ The else-if Ladder

FormUse it whenBranches run
ifone optional action0 or 1
if - elseexactly two outcomesexactly 1
if - else if - elseseveral outcomes, only one should runexactly 1 (the first true one)
nested ifa second question depends on the firstdepends

Figure 2: The four shapes of if statements.

When there are more than two outcomes, chain the tests. Java checks them from the top and runs the first block whose condition is true, then skips the rest.

marks>= 90?>= 75?>= 60?>= 40?Grade
95yes–––A
82noyes––B
67nonoyes–C
45nononoyesD
20nonononoF
Java checks from the top and stops at the first true test. A dash means that test is never reached.

Figure 3: How the else-if ladder is evaluated for each mark.

Program 3: Grade calculator

public class GradeLadder {
    public static void main(String[] args) {
        int[] tests = {95, 82, 67, 45, 20};
        for (int marks : tests) {
            String grade;
            if (marks >= 90) {
                grade = "A";
            } else if (marks >= 75) {
                grade = "B";
            } else if (marks >= 60) {
                grade = "C";
            } else if (marks >= 40) {
                grade = "D";
            } else {
                grade = "F";
            }
            System.out.println(marks + " -> " + grade);
        }
    }
}
🖥️ Output:
95 -> A
82 -> B
67 -> C
45 -> D
20 -> F
  • The program tests five marks. The loop and array are covered in Lessons 19 and 21, so for now read it as “repeat this for each mark”.
  • Because tests run top to bottom, 82 does not need to be written as “between 75 and 89”. The earlier test (>= 90) already failed.
  • The final else catches everything left over.
  • Order matters. If you put marks >= 40 first, every passing mark would become D.

4️⃣ Nested if

An if inside another if handles a second question that only matters when the first answer is yes.

public class NestedIf {
    public static void main(String[] args) {
        int age = 20;
        boolean hasId = true;
        if (age >= 18) {
            if (hasId) {
                System.out.println("Entry allowed");
            } else {
                System.out.println("Show your ID");
            }
        } else {
            System.out.println("Too young");
        }

        int a = 12, b = 45, c = 30;
        int largest;
        if (a >= b && a >= c) {
            largest = a;
        } else if (b >= c) {
            largest = b;
        } else {
            largest = c;
        }
        System.out.println("Largest of " + a + ", " + b + ", " + c + " = " + largest);
    }
}
🖥️ Output:
Entry allowed
Largest of 12, 45, 30 = 45
  • The ID check happens only for adults.
  • For the largest of three, the logical && from Lesson 13 checks that a beats both others. If not, only b and c remain to compare.

5️⃣ Braces and the Dangling else

Without braces, an if controls only the next one statement. Indentation does not matter to Java. An else belongs to the nearest if.

public class DanglingElse {
    public static void main(String[] args) {
        int x = 5;
        if (x > 0)
            System.out.println("positive");
            System.out.println("this line always runs");

        int y = -3;
        if (y > 0)
            if (y > 10)
                System.out.println("big");
            else
                System.out.println("belongs to the inner if");
        System.out.println("end");
    }
}
🖥️ Output:
positive
this line always runs
end
  • The second println looks like part of the if because it is indented, but it is not. Only the first line belongs to it.
  • For y = -3 the outer if is false, so nothing inside runs. The else was attached to the inner if, not the outer one, so no message prints.
  • Using braces everywhere removes this confusion.

6️⃣ Errors Beginners Meet

A stray else

public class Bad1 {
    public static void main(String[] args) {
        int x = 5;
        if (x > 3)
            System.out.println("big");
        else
            System.out.println("small");
        else
            System.out.println("never");
    }
}
🖥️ Compiler message:
Bad1.java:8: error: ‘else’ without ‘if’
else
^
1 error
  • Every else needs its own if. To test another condition, write else if (...).

Variable might not have been initialized

public class Bad3 {
    public static void main(String[] args) {
        String grade;
        int marks = 50;
        if (marks >= 40) {
            grade = "Pass";
        }
        System.out.println(grade);
    }
}
🖥️ Compiler message:
Bad3.java:8: error: variable grade might not have been initialized
System.out.println(grade);
^
1 error
  • If the condition were false, grade would never get a value. Add an else that assigns it, or give it a starting value.

The semicolon after if: no error, wrong behaviour

public class Bad2 {
    public static void main(String[] args) {
        int x = 5;
        if (x > 3);
        {
            System.out.println("always printed");
        }
        if (x > 100) ;
            System.out.println("also always printed");
    }
}
🖥️ Compiler warnings (javac -Xlint:all), then the run:
Bad2.java:4: warning: [empty] empty statement after if
if (x > 3);
^
Bad2.java:8: warning: [empty] empty statement after if
if (x > 100) ;
^
2 warnings

always printed
also always printed
  • The ; ends the if with an empty statement, so the next lines are not controlled by it. Even x > 100 is false, yet the message prints. Never put a semicolon right after the closing bracket of if.

⚠️ Common Mistakes

MistakeProblemFix
if (x = 5)Assignment, not comparison (a compile error in Java)if (x == 5)
if (x > 3);Empty statement; the block always runsRemove the semicolon
No braces, then adding a second lineSecond line is not controlled by the ifAlways use braces
Ladder in the wrong orderWide tests catch everything firstTest the most specific condition first
Comparing Strings with ==Compares referencesUse equals()
Separate ifs instead of else ifSeveral blocks may runUse else if for exclusive choices

❓ Frequently Asked Questions

Q1. Can an if condition be an int, like in C?
No. It must be a boolean. if (1) is a compile error in Java.

Q2. How many else-if blocks can I have?
As many as you need, but for many fixed values a switch (Lesson 17) is neater.

Q3. Is else compulsory?
No. An if can stand alone.

Q4. What is the difference between else if and separate ifs?
In an else-if chain only the first true block runs. With separate ifs every true block runs.

✅ Key Takeaways

  • if runs a block when its boolean condition is true.
  • else gives the other path, and else if adds more tests, checked top to bottom.
  • Only the first true block in a ladder runs.
  • Always use braces. Never put ; after the condition.
  • An else belongs to the nearest if.
🎓 Practice questions: (1) Write a program that reads a number and prints whether it is positive, negative or zero. (2) Check whether a year is a leap year (divisible by 4, but not by 100 unless also by 400). (3) Read three sides and print whether they form a triangle. (4) Why does the order of tests matter in an else-if ladder? (5) Find the bug: if (marks > 40); System.out.println("Pass");
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision