Skip to content
elephantoo

Decisions: if/else & switch

Lesson 5 of 43 14 min read

if, else if, else, nested conditions, the classic switch and modern switch expressions.


So far every statement ran from top to bottom. Real programs need to choose: charge shipping only for small orders, show an error only when the password is wrong. This lesson covers Java's decision-making tools: if, else, and switch. In the next lesson we look at loops.

if: run code only when a condition is true#

Java
int temperature = 32;

if (temperature > 30) {
    System.out.println("It's hot! Stay hydrated.");
}

The condition inside ( ) must be a boolean expression. Unlike C or JavaScript, Java does not treat numbers as true/false: if (1) is a compile error.

if / else#

Java
int age = 16;

if (age >= 18) {
    System.out.println("You can vote.");
} else {
    System.out.println("Not yet! " + (18 - age) + " years to go.");
}

Exactly one of the two blocks runs.

else if chains#

When there are more than two possibilities, chain conditions. Java checks them top to bottom and runs only the first block whose condition is true:

Grades.java
public class Grades {
    public static void main(String[] args) {
        int[] scores = {95, 82, 71, 40};
        for (int score : scores) {       // loop over each score (next lesson!)
            String grade;
            if (score >= 90) {
                grade = "A";
            } else if (score >= 80) {
                grade = "B";
            } else if (score >= 70) {
                grade = "C";
            } else {
                grade = "F";
            }
            System.out.println(score + " -> " + grade);
        }
    }
}
Output
95 -> A
82 -> B
71 -> C
40 -> F

Order matters: if you tested score >= 70 first, a 95 would get a C. Put the most specific (or highest) condition first.

Combining conditions#

Use the logical operators from the previous lesson:

Java
boolean isWeekend = true;
int hour = 10;

if (isWeekend && hour < 12) {
    System.out.println("Lazy brunch time");
}

if (hour < 6 || hour > 22) {
    System.out.println("Quiet hours");
}

if (!isWeekend) {
    System.out.println("Work day");
}

Nested if#

You can put an if inside another. Keep nesting shallow, as deep nesting is hard to read:

Java
if (loggedIn) {
    if (isAdmin) {
        System.out.println("Admin dashboard");
    } else {
        System.out.println("User dashboard");
    }
} else {
    System.out.println("Please log in");
}

A common way to flatten nesting is to handle special cases first and return early. You will see this pattern in the methods lesson.

Always use braces#

Braces are optional when a block has one statement, but skipping them invites bugs:

Java
if (balance < 0)
    System.out.println("Overdrawn!");
    sendAlert();   // runs EVERY time: indentation does not create blocks!

Only the first statement belongs to the if. Always write the braces and this bug can never happen.

Comparing values correctly#

ComparingUse
Primitive numbers, char, boolean==, !=, <, >...
Strings and other objectsa.equals(b)
Strings, ignoring casea.equalsIgnoreCase(b)
CompareStrings.java
public class CompareStrings {
    public static void main(String[] args) {
        String a = "hi";
        String b = new String("hi");
        System.out.println(a == b);          // different objects
        System.out.println(a.equals(b));     // same characters
        String cmd = "QUIT";
        System.out.println("quit".equalsIgnoreCase(cmd));
    }
}
Output
false
true
true

Tip: write "quit".equals(input) rather than input.equals("quit"). If input is null, the first form simply returns false while the second throws a NullPointerException.

The classic switch statement#

When you branch on one value with many possible options, switch is cleaner than a long else if chain. It works with int (and smaller integer types), char, String and enums.

ClassicSwitch.java
public class ClassicSwitch {
    public static void main(String[] args) {
        int day = 3;
        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            default:
                System.out.println("Another day");
        }
    }
}
Output
Wednesday

Each case label is a possible value; default runs when nothing matches. The break is crucial: without it, execution falls through into the next case:

FallThrough.java
public class FallThrough {
    public static void main(String[] args) {
        int level = 2;
        switch (level) {
            case 1:
                System.out.println("Level 1");
            case 2:
                System.out.println("Level 2");
            case 3:
                System.out.println("Level 3");
            default:
                System.out.println("Done");
        }
    }
}
Output
Level 2
Level 3
Done

Forgotten breaks are a notorious source of bugs, which is why modern Java added a better form.

The modern switch (Java 14+)#

Arrow cases (->) never fall through, can list several values separated by commas, and need no break:

Java
String day = "SAT";
switch (day) {
    case "MON", "TUE", "WED", "THU", "FRI" -> System.out.println("Weekday");
    case "SAT", "SUN" -> System.out.println("Weekend!");
    default -> System.out.println("Unknown day");
}

switch as an expression

Even better, a switch can produce a value that you assign or return:

SwitchExpression.java
public class SwitchExpression {
    public static void main(String[] args) {
        int month = 2;
        int year = 2024;
        boolean isLeap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;

        int days = switch (month) {
            case 1, 3, 5, 7, 8, 10, 12 -> 31;
            case 4, 6, 9, 11 -> 30;
            case 2 -> {
                System.out.println("Checking leap year...");
                yield isLeap ? 29 : 28;
            }
            default -> throw new IllegalArgumentException("Bad month: " + month);
        };

        System.out.println("Days: " + days);
    }
}
Output
Checking leap year...
Days: 29
  • A simple arrow case gives its value directly: case 4, 6, 9, 11 -> 30;
  • A case that needs several statements uses a block, and yield hands back the value.
  • A switch expression must be exhaustive: every possible input must produce a value or throw. For int or String that means a default is required. For enums, covering every constant is enough.

In Java 21, switch can also match on types and patterns (case Circle c -> ...). You will meet that in the modern Java lesson.

if or switch?#

Use if/else when...Use switch when...
conditions are ranges (score >= 90)you compare one value against fixed constants
conditions involve different variablesthere are many options (more than 3 or so)
you have just one or two branchesyou want a value back (switch expression)

A worked example: shipping calculator#

Shipping.java
public class Shipping {
    public static void main(String[] args) {
        double orderTotal = 749.0;
        String zone = "remote";
        boolean isMember = false;

        double shipping;
        if (orderTotal >= 999 || isMember) {
            shipping = 0;
        } else {
            shipping = switch (zone) {
                case "local" -> 40;
                case "national" -> 80;
                case "remote" -> 150;
                default -> throw new IllegalArgumentException("Unknown zone " + zone);
            };
        }

        System.out.println("Shipping: " + shipping);
        System.out.println("Total: " + (orderTotal + shipping));
    }
}
Output
Shipping: 150.0
Total: 899.0

Common mistakes#

  • Putting a semicolon after the condition: if (x > 5); ends the if right there, and the block below always runs.
  • Using = instead of == in a condition.
  • Comparing strings with ==.
  • Forgetting break in an old-style switch. Prefer arrow cases.
  • Ordering else if conditions so a broad case hides a narrower one.

What's next#

Your programs can now choose between paths. Next we make them repeat work with for, while and do-while loops.

Check your understanding

Quick quiz

0/3 answered
  1. 1.What is printed? int t = 25; if (t > 30) System.out.println("hot"); else if (t > 20) System.out.println("warm"); else if (t > 10) System.out.println("mild");

  2. 2.In an old-style switch statement with case 1: labels, what happens if you forget break?

  3. 3.In a modern switch expression, which keyword produces the value from a block { ... }?

Finished reading?

Mark this lesson complete to track your progress.