Java if, else if and else

Make decisions with comparison operators, if, else if, else, logical operators and switch.

Lesson 18 of 127Beginner18 min read

A program that always does the same thing isn't very useful. Conditions let your code react: show a warning if the battery is low, give a discount if the basket is big enough, end the game when the lives run out.

In Java, an if statement checks a boolean expression, something that is either true or false, and runs a block of code only when it's true. You can add else if branches for more cases and an else for everything else. For choosing between many fixed values, Java also has switch.

In this lesson you'll write conditions, combine them with logical operators, compare text correctly and use switch.

Comparison operators

OperatorMeaningExample
==equal to (numbers, chars, booleans)lives == 0
!=not equal tolevel != 1
> <greater / less thanscore > 100
>= <=greater or equal / less or equalage >= 18

Each comparison produces a boolean. You can store it, boolean isAdult = age >= 18;, or use it directly in an if.

if, else if, else

Java
int battery = 15;

if (battery < 10) {
    System.out.println("Critical: plug in now");
} else if (battery < 20) {
    System.out.println("Low battery");
} else {
    System.out.println("Battery OK");
}
  • The condition goes in round brackets, and the code to run goes in curly braces.
  • Java checks from top to bottom and runs only the first block whose condition is true.
  • else has no condition and catches every remaining case.

Logical operators

  • && (and): true only if both sides are true.
  • || (or): true if at least one side is true.
  • ! (not): turns true into false and false into true.
Java
if (age >= 12 && hasTicket) { ... }
if (day.equals("Sat") || day.equals("Sun")) { ... }
if (!isLoggedIn) { ... }

For a quick either/or value, the ternary operator fits on one line: String label = score >= 50 ? "Pass" : "Fail";

Short-circuit evaluation

&& and || are short-circuit operators: Java stops evaluating as soon as the answer is known. With &&, if the left side is false the whole expression must be false, so the right side is never run. With ||, if the left side is true the right side is skipped.

That makes && the safe way to guard a check that would otherwise crash:

Java
if (name != null && name.length() > 3) {
    System.out.println("Long enough");
}

If name is null, the left side is false and name.length() is never called, so there's no NullPointerException. Order matters: written the other way round, the length check would run first and fail. The boolean expressions lesson looks at evaluation order in more depth.

Nested conditions and early returns

An if can sit inside another if when the second question only makes sense after the first has been answered:

Java
if (isMember) {
    if (basketTotal >= 50) {
        System.out.println("Free delivery and 10% off");
    } else {
        System.out.println("10% off");
    }
}

Deep nesting quickly becomes hard to follow. Two habits keep conditions readable: combine conditions with && when both must be true, and inside methods, handle the unusual cases first and return early, so the main logic isn't buried four levels deep. The nested conditions lesson practises both techniques.

Comparing Strings and switch

Use .equals() to compare the text of two Strings, not ==. The == operator checks whether two variables point to the same object in memory, which can give surprising results. equalsIgnoreCase() ignores capital letters.

When one value is compared with many fixed options, switch is tidier than a long chain:

Java
switch (day) {
    case "Sat", "Sun" -> System.out.println("Weekend");
    case "Fri" -> System.out.println("Almost there");
    default -> System.out.println("Weekday");
}

This arrow form works in Java 14 and later. default runs when no case matches.

Java if else Syntax

if / else if / else and switch

if (condition) {
    // runs when condition is true
} else if (otherCondition) {
    // runs when the first was false and this is true
} else {
    // runs when nothing matched
}

switch (value) {
    case A -> statement;
    case B, C -> statement;
    default -> statement;
}

Java if else Summary

  • Comparisons give booleans; if (condition) { } runs when it's true.
  • Use else if for more checks and else for everything else. Only one branch runs.
  • Combine conditions with &&, || and !.
  • Compare String text with .equals(), never ==.
  • switch chooses between many fixed values; default handles the rest.

Java if else Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Ticket prices

Java
public class Main {
    public static void main(String[] args) {
        int age = 67;
        double price;

        if (age < 5) {
            price = 0;
        } else if (age < 16) {
            price = 6.50;
        } else if (age >= 65) {
            price = 7.00;
        } else {
            price = 11.00;
        }

        System.out.println("Ticket: " + price);
    }
}
Output
Ticket: 7.0
Line-by-line explanation
  1. Line 4The variable is declared before the if so every branch can set it.
  2. Lines 6 to 1267 isn't under 5 or under 16, but it is 65 or over, so that branch runs.
  3. Line 16Java prints 7.00 as 7.0. You'll see how to format money later.
Example 2

Logical operators and a ternary

Java
public class Main {
    public static void main(String[] args) {
        int temp = 24;
        boolean raining = false;

        if (temp > 20 && !raining) {
            System.out.println("Picnic day!");
        }

        String coat = (temp < 12 || raining) ? "Bring a coat" : "No coat needed";
        System.out.println(coat);
    }
}
Output
Picnic day!
No coat needed
Line-by-line explanation
  1. Line 6Both parts are true: 24 is above 20 and it isn't raining.
  2. Line 10The ternary picks one of two values. The condition is false, so the second one is used.
Example 3

Checking a password and a menu choice

Java
public class Main {
    public static void main(String[] args) {
        String password = "sunflower";
        String typed = "Sunflower";

        if (typed.equals(password)) {
            System.out.println("Welcome back");
        } else if (typed.equalsIgnoreCase(password)) {
            System.out.println("Check your Caps Lock");
        } else {
            System.out.println("Wrong password");
        }

        int choice = 2;
        switch (choice) {
            case 1 -> System.out.println("New game");
            case 2 -> System.out.println("Load game");
            default -> System.out.println("Quit");
        }
    }
}
Output
Check your Caps Lock
Load game
Line-by-line explanation
  1. Line 6equals() is case-sensitive, so "Sunflower" doesn't match.
  2. Line 8equalsIgnoreCase() ignores case, so this branch runs.
  3. Lines 15 to 19switch jumps straight to the matching case.

Common Java if else Mistakes

Comparing Strings with ==

Don't
if (answer == "yes") { ... }
Do
if (answer.equals("yes")) { ... }

== checks whether both variables refer to the same object, which can be false even when the text is identical.

A semicolon after the condition

Don't
if (score > 100); {
    System.out.println("High score!");
}
Do
if (score > 100) {
    System.out.println("High score!");
}

The semicolon ends the if, so the block below always runs.

Using = in a condition

Don't
if (lives = 0) { ... }
Do
if (lives == 0) { ... }

A single = assigns a value; Java reports "incompatible types: int cannot be converted to boolean".

Java if else in Real Projects

Decisions in real apps

An Android app checks if (permissionGranted) before using the camera, a shop's server checks if (cart.total() >= 50) before removing delivery charges, and a game's main loop checks if (player.isDead()) many times every second. Conditions are everywhere.

Java if else FAQ

Can an if condition use a number in Java?

No. Unlike C or JavaScript, Java only accepts a boolean in a condition. if (count) doesn't compile; write if (count != 0) or if (count > 0). This rule is why the classic mistake if (x = 5) is caught by the compiler in Java.

What is the difference between & and && in Java?

Both give true when both sides are true, but && short-circuits and skips the right side when the left side is false, while & always evaluates both sides. Use && in conditions. & is mainly used as a bitwise operator on integers, where 5 & 3 is 1.

Is the else block required?

No. An if on its own runs its block when the condition is true and does nothing otherwise. Add else only when something must happen in the false case too.

How many else if branches can I use?

As many as you need; Java has no limit. Order matters, because only the first true branch runs, so put the most specific conditions first. When a long chain compares one variable with fixed values, a switch is usually clearer.

Should I nest ternary operators?

It's allowed, but a nested ternary such as a > b ? (a > c ? a : c) : (b > c ? b : c) is hard to read. Use a ternary for a simple either/or value and an if/else chain, or Math.max, for anything more involved.

Java if else Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the code so it prints "Even" for even numbers and "Odd" otherwise.

int n = 8;
 (n % 2 == 0) {
    System.out.println("Even");
}  {
    System.out.println("Odd");
}
Predict the outputeasy

What does this print?

int x = 15;
if (x > 10) {
    System.out.println("A");
} else if (x > 5) {
    System.out.println("B");
} else {
    System.out.println("C");
}
Multiple choicemedium

Which condition is true only when both hasKey and doorClosed are true?

Predict the outputmedium

What does this print?

int score = 45;
String result = score >= 50 ? "Pass" : "Retry";
System.out.println(result);
Predict the outputmedium

What does this print?

int t = 25;
System.out.println(t > 30 ? "hot" : t > 20 ? "warm" : "cool");

Java if else Quiz

5 questions to check what you learned.

  1. Where does the condition of an if statement go?

    • In curly braces
    • After a colon
    • In round brackets
    • In square brackets
  2. How should you check whether two Strings contain the same text?

    • a == b
    • a.equals(b)
    • a = b
    • a.compare(b)
  3. What does !true evaluate to?

    • false
    • true
    • 0
    • An error
  4. In a switch statement, when does default run?

    • Always, after the matching case
    • When none of the cases match
    • Before any case
    • Only for numbers
  5. Why compare Strings with .equals() instead of ==?

    • == is slower
    • equals ignores capitals
    • == doesn't compile with Strings
    • == checks whether they're the same object, not whether the text matches