if & else

Java · Lesson 9 of 32 6 min read Updated

Programs become useful when they make decisions. Should this customer get free delivery? Did the student pass? Is the PIN correct? In Java, the if statement runs a block of code only when a condition is true, and else gives an alternative when it is false.

In this lesson you will write if, else and else if chains, combine conditions with the logical operators from Operators & Math, and learn the mistakes that trip up nearly every beginner.

The if statement

The condition goes in round brackets and must be a boolean expression: something that is either true or false. The code to run goes in curly braces.

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

        if (age >= 18) {
            System.out.println("You can vote in the election.");
        } else {
            int yearsLeft = 18 - age;
            System.out.println("Wait " + yearsLeft + " more year(s) to vote.");
        }
        System.out.println("Checked age " + age);
    }
}
Output
Wait 1 more year(s) to vote.
Checked age 17

Exactly one of the two blocks runs. After the if/else, the program continues with the next statement, so Checked age 17 is always printed. The variable yearsLeft exists only inside the else block; this region is called its scope, and using yearsLeft after the closing brace would be a compile error.

else if chains

When there are more than two possibilities, chain conditions with else if. Java checks them from top to bottom and runs only the first block whose condition is true. The final else catches everything else.

Java
public class Grade {
    public static void main(String[] args) {
        int[] allMarks = {92, 76, 58, 41, 30};

        for (int marks : allMarks) {
            String grade;
            if (marks >= 90) {
                grade = "A+";
            } else if (marks >= 75) {
                grade = "A";
            } else if (marks >= 60) {
                grade = "B";
            } else if (marks >= 33) {
                grade = "C";
            } else {
                grade = "Fail";
            }
            System.out.println(marks + " -> " + grade);
        }
    }
}
Output
92 -> A+
76 -> A
58 -> C
41 -> C
30 -> Fail

The for line simply repeats the decision for each mark in the list; you will learn it in Loops. Because the checks run in order, the condition for "A" does not need to say marks < 90: any mark of 90 or more was already caught by the first branch. Order matters. If you put marks >= 33 first, everyone who passed would get a C.

The compiler also checks that grade gets a value on every path. If you remove the final else, you get error: variable grade might not have been initialized, because Java cannot be sure one of the branches ran.

Combining conditions

Use && (and), || (or) and ! (not) to build richer conditions. Brackets make your intention clear when you mix them.

Java
public class Museum {
    public static void main(String[] args) {
        int basePrice = 200;
        int age = 67;
        boolean isStudent = false;
        boolean isWeekend = true;

        int price;
        if (age < 5) {
            price = 0;
        } else if (age >= 60 || isStudent) {
            price = basePrice / 2;
        } else {
            price = basePrice;
        }

        if (isWeekend && price > 0) {
            price += 20;    // weekend charge
        }
        System.out.println("Museum ticket: Rs " + price);
    }
}
Output
Museum ticket: Rs 120

Here is a classic combined condition: the leap year rule. A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400.

Java
public class Leap {
    public static void main(String[] args) {
        int[] years = {2024, 2026, 1900, 2000};
        for (int year : years) {
            boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
            System.out.println(year + (leap ? " is" : " is not") + " a leap year");
        }
    }
}
Output
2024 is a leap year
2026 is not a leap year
1900 is not a leap year
2000 is a leap year

Storing the result in a well-named boolean variable such as leap often makes a complicated if much easier to read.

Strings in conditions and nested if

Remember from Strings & Text Blocks: compare text with equals or equalsIgnoreCase, never ==. You can also put an if inside another if; this is called nesting.

Java
public class Login {
    public static void main(String[] args) {
        String savedUser = "meera.k";
        String savedPin = "4821";

        String typedUser = "Meera.K";
        String typedPin = "4821";

        if (typedUser.equalsIgnoreCase(savedUser)) {
            if (typedPin.equals(savedPin)) {
                System.out.println("Welcome back, Meera!");
            } else {
                System.out.println("Wrong PIN.");
            }
        } else {
            System.out.println("Unknown user.");
        }
    }
}
Output
Welcome back, Meera!

Usernames often ignore case, but PINs and passwords must match exactly. Nesting more than two or three levels deep makes code hard to follow. When that happens, combine conditions with &&, or move the checks into a method that returns early (you will see this in Methods & Overloading).

Common mistakes

  • Using = instead of ==. if (x = 5) fails with error: incompatible types: int cannot be converted to boolean. Use == to compare. (Java's strict typing saves you here; in C this bug compiles.)
  • A semicolon after the condition. if (balance > 1000); ends the if with an empty statement, so the block after it always runs. Never put ; right after if (...).
  • Comparing strings with ==. Use equals.
  • Comparing decimals with ==. 0.1 + 0.2 == 0.3 is false because of binary rounding. Check whether the difference is tiny instead: Math.abs(a - b) < 1e-9.
  • Wrong order in an else if chain. Put the most specific or strictest condition first.

Key points

  • if (condition) { ... } runs the block only when the condition is true; else handles the other case.
  • else if chains are checked from top to bottom, and only the first matching branch runs.
  • Combine conditions with &&, || and !, and use brackets for clarity.
  • Compare strings with equals, not ==.
  • Variables declared inside a block exist only inside that block.
  • Always use braces, and never put a semicolon straight after if (...).

Exercise

An online store in Rohtak charges delivery like this: free if the order is Rs 499 or more, or if the customer is a member; otherwise Rs 25 for customers in Rohtak or Panipat, and Rs 60 for everyone else. Write Delivery.java with the order value 349, the city "Rohtak" and member status false, and print the delivery charge and the total.

Show solution
Java
public class Delivery {
    public static void main(String[] args) {
        int orderValue = 349;
        String city = "Rohtak";
        boolean isMember = false;

        int deliveryCharge;
        if (orderValue >= 499 || isMember) {
            deliveryCharge = 0;
        } else if (city.equals("Rohtak") || city.equals("Panipat")) {
            deliveryCharge = 25;
        } else {
            deliveryCharge = 60;
        }
        System.out.println("Delivery charge: Rs " + deliveryCharge);
        System.out.println("Total: Rs " + (orderValue + deliveryCharge));
    }
}
Output
Delivery charge: Rs 25
Total: Rs 374

The free-delivery rule comes first because it applies whatever the city is. Try changing orderValue to 520 or city to "Pune" and check that the charge changes as expected.

Quick Quiz

1. In an else if chain, how many branches run?

2. What is wrong with if (total > 500); { System.out.println("Free gift"); }?

3. Which condition checks whether city is "Jaipur", ignoring capital letters?

4. What does if (count = 0) do in Java?

Learn Java with a mentor

Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call