Java if, else and switch: Making Decisions in Your Code

admin5 min read
In this tutorial
  1. The if statement
  2. if-else
  3. else if chains
  4. Nested if statements
  5. Always use braces
  6. The classic switch statement
  7. Modern switch expressions (Java 14+)
  8. if or switch?
  9. Common mistakes
  10. Practice
  11. Summary

Programs become useful when they can react differently to different situations: approve a payment or decline it, show a pass or fail grade, pick a delivery fee based on the city. In Java you make these decisions with if statements and switch.

This tutorial walks through each form, shows when to use which, and covers the modern switch expressions available since Java 14.

The if statement

An if runs a block of code only when its condition is true:

int balance = 5000;
int amount = 3000;

if (amount <= balance) {
    balance -= amount;
    System.out.println("Payment approved. New balance: " + balance);
}

The condition must be a boolean expression. Unlike some languages, Java will not treat 0 or an empty string as false: if (count) does not compile when count is an int.

if-else

Add else to handle the case where the condition is false:

if (amount <= balance) {
    System.out.println("Payment approved");
} else {
    System.out.println("Insufficient funds");
}

else if chains

When you have more than two outcomes, chain conditions with else if. Java checks them from top to bottom and runs the first one that matches:

public class Grades {
    static char grade(int score) {
        if (score >= 70) {
            return 'A';
        } else if (score >= 60) {
            return 'B';
        } else if (score >= 50) {
            return 'C';
        } else if (score >= 45) {
            return 'D';
        } else {
            return 'F';
        }
    }

    public static void main(String[] args) {
        int[] scores = {82, 64, 51, 47, 30};
        for (int s : scores) {
            System.out.println(s + " -> " + grade(s));
        }
    }
}

Order matters. If you checked score >= 45 first, every passing score would get a D.

Nested if statements

You can put an if inside another if, but deep nesting quickly becomes hard to read:

if (user != null) {
    if (user.isActive()) {
        if (user.hasRole("ADMIN")) {
            showDashboard();
        }
    }
}

Two ways to flatten it:

  1. Combine conditions with &&: if (user != null && user.isActive() && user.hasRole("ADMIN")).
  2. Use guard clauses that return early:
void openDashboard(User user) {
    if (user == null) return;
    if (!user.isActive()) return;
    if (!user.hasRole("ADMIN")) return;
    showDashboard();
}

Guard clauses keep the “happy path” at the left margin, which most developers find easier to follow.

Always use braces

Java lets you skip the braces when a branch has a single statement, but it is a trap:

if (isLoggedIn)
    System.out.println("Welcome");
    loadProfile(); // runs every time! It is NOT part of the if

Indentation means nothing to the compiler. Always use { }, even for one line.

The classic switch statement

When you compare one value against many constants, switch is often cleaner than a long else if chain:

String day = "SAT";

switch (day) {
    case "SAT":
    case "SUN":
        System.out.println("Weekend");
        break;
    case "FRI":
        System.out.println("Almost weekend");
        break;
    default:
        System.out.println("Weekday");
}

switch works with int, char, String, enums and their wrapper types. Note the break statements: without them, execution falls through into the next case. Forgetting a break is one of the most common switch bugs.

Modern switch expressions (Java 14+)

Java 14 made switch expressions standard. They use arrows, never fall through, and can return a value:

public class DeliveryFee {
    enum City { LAGOS, ABUJA, IBADAN, PORT_HARCOURT, KANO }

    static int fee(City city) {
        return switch (city) {
            case LAGOS -> 1500;
            case IBADAN -> 2500;
            case ABUJA, PORT_HARCOURT -> 3500;
            case KANO -> 4000;
        };
    }

    public static void main(String[] args) {
        for (City c : City.values()) {
            System.out.println(c + ": NGN " + fee(c));
        }
    }
}

Notice:

  • Multiple labels can share one branch: case ABUJA, PORT_HARCOURT.
  • No break is needed.
  • When switching over an enum and every constant is covered, you do not need a default. If someone adds a new city later, the compiler will tell you this switch is no longer exhaustive. That is a big safety win.

If a branch needs several statements, use a block and yield the result:

String label = switch (statusCode) {
    case 200 -> "OK";
    case 404 -> "Not found";
    default -> {
        System.out.println("Unexpected status: " + statusCode);
        yield "Error";
    }
};

if or switch?

  • Use if/else for ranges and complex conditions (score >= 70, age > 18 && hasId).
  • Use switch when you compare one value against a list of fixed constants, especially enums.
  • Prefer switch expressions over the old statement form in new code: they are shorter and safer.

Common mistakes

  • Using = instead of ==. if (x = 5) does not compile for int, but if (isDone = true) compiles for boolean and is always true. Write if (isDone) instead.
  • Comparing strings with == inside conditions. Use equals(), or switch on the string.
  • Switching on a null string. switch (null) throws a NullPointerException. Check for null first.
  • Unreachable else-if branches because a broader condition comes earlier.

Practice

  1. Write a method that returns “child”, “teen”, “adult” or “senior” for a given age.
  2. Rewrite it using guard clauses and early returns.
  3. Create an enum Size { SMALL, MEDIUM, LARGE } and use a switch expression to return the price of a drink.

Summary

  • if, else if and else cover any decision; order your conditions carefully.
  • Use guard clauses instead of deep nesting, and always use braces.
  • Classic switch statements fall through unless you break.
  • Switch expressions with -> return values, never fall through and can be checked for completeness by the compiler.

Next, learn to repeat work with loops in Java.

Ask a question or leave a comment

Your email address will not be published. Required fields are marked *