Java switch

Choose between many options with switch: the classic statement with break, modern arrow cases, multiple labels, switch expressions that return values, and yield.

Lesson 20 of 127Beginner18 min read

When a program has to choose between several fixed options, such as a day of the week, a menu choice or a status code, a long chain of if, else if, else if gets repetitive and hard to scan. Java's switch is designed for exactly this: it looks at one value and jumps to the matching case.

You saw a short switch in the if-else lesson. Java's switch has changed a lot over the years. The classic version, with break after every case, is still everywhere in existing code. Modern Java (version 14 and later) adds arrow cases and switch expressions, which are shorter, safer and can return a value directly.

In this lesson you'll learn both styles, understand the "fall-through" behaviour that causes classic bugs, combine several values in one case, return values from a switch, and decide when switch is the right tool and when if-else is better.

The classic switch statement

Java
switch (day) {
    case "Sat":
        System.out.println("Weekend!");
        break;
    case "Mon":
        System.out.println("Back to work");
        break;
    default:
        System.out.println("A weekday");
}
  • Java compares the value in brackets with each case label and starts running at the match.
  • break jumps out of the switch. Without it, execution falls through into the next case's code, even if that label doesn't match.
  • default runs when nothing matches, like a final else.
  • You can switch on int, char, String and enum values, but not on double or boolean.

Arrow cases

Modern Java lets you write case value -> instead of case value:. Arrow cases never fall through, so there's no break to forget:

Java
switch (day) {
    case "Sat", "Sun" -> System.out.println("Weekend!");
    case "Mon" -> System.out.println("Back to work");
    default -> System.out.println("A weekday");
}
  • Several labels can share one case, separated by commas.
  • The right side of the arrow is a single statement, or a block in { } if you need several lines.
  • For new code, prefer arrow cases: they're shorter and avoid a whole class of bugs.

Switch expressions

A switch can also be an expression that produces a value, which you can store or return:

Java
int days = switch (month) {
    case 2 -> 28;
    case 4, 6, 9, 11 -> 30;
    default -> 31;
};

Note the semicolon after the closing brace: the whole switch is part of an assignment statement. A switch expression must cover every possible value, so it almost always needs a default. If a case needs several lines before giving its value, use a block and the keyword yield to hand back the result.

switch or if-else?

Use switch whenUse if-else when
You compare one value against fixed optionsConditions involve ranges, like score >= 70
There are many options, such as menu choicesYou combine conditions with && and ||
You want a value for each optionYou compare several different variables

Switch works especially well with enums: for an enum, the compiler can check that a switch expression handles every constant, so adding a new one later shows you every switch that needs updating. Java 21 also lets switch match on types and conditions ("pattern matching"), which you'll meet in newer code.

Switching on null and on types

A classic switch on a String or enum that happens to be null throws a NullPointerException before any case is checked, and even default doesn't catch it. Check for null before switching, or, from Java 21, add a case null label:

Java
switch (command) {
    case null -> System.out.println("No command given");
    case "start" -> System.out.println("Starting");
    default -> System.out.println("Unknown command");
}

Java 21 also allows type patterns with optional when guards, which test what kind of object a value is and bind it to a variable:

Java
Object value = 7;
String text = switch (value) {
    case Integer i when i > 5 -> "a large number";
    case Integer i -> "a small number";
    case String s -> "the text " + s;
    default -> "something else";
};

Cases are checked in order, so the guarded case must come before the plain Integer case. The switch expressions lesson covers these modern forms in detail.

Java switch Syntax

switch forms

// classic statement
switch (value) {
    case A: ...; break;
    default: ...;
}

// arrow statement
switch (value) {
    case A, B -> ...;
    default -> ...;
}

// expression
Type result = switch (value) {
    case A -> x;
    case B -> { ...; yield y; }
    default -> z;
};

Java switch Summary

  • switch compares one value with several case labels; default handles everything else.
  • Classic case x: labels fall through without break; arrow case x -> labels never fall through.
  • Several labels can share one case: case "Sat", "Sun" ->.
  • A switch expression returns a value; it must cover every case and ends with a semicolon.
  • Use yield to return a value from a multi-line case block.

Java switch Examples

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

Example 1

A menu with arrow cases

Java
public class Main {
    public static void main(String[] args) {
        String[] choices = {"1", "2", "3", "9"};
        for (String choice : choices) {
            switch (choice) {
                case "1" -> System.out.println("Starting a new game");
                case "2" -> System.out.println("Loading saved game");
                case "3" -> System.out.println("Opening settings");
                default -> System.out.println("Unknown option: " + choice);
            }
        }
    }
}
Output
Starting a new game
Loading saved game
Opening settings
Unknown option: 9
Line-by-line explanation
  1. Lines 3 to 4The loop tries four inputs, as if a player typed them.
  2. Line 5Switching on a String compares with equals(), so it's safe for text.
  3. Line 9default catches anything that isn't a valid option.
Example 2

A switch expression with yield

Java
public class Main {
    static String shipping(String country, double weightKg) {
        return switch (country) {
            case "UK" -> "£3.99";
            case "FR", "DE", "ES" -> "£7.50";
            default -> {
                double cost = 10 + weightKg * 2;
                yield String.format("£%.2f", cost);
            }
        };
    }

    public static void main(String[] args) {
        System.out.println(shipping("UK", 1));
        System.out.println(shipping("DE", 1));
        System.out.println(shipping("US", 3.5));
    }
}
Output
£3.99
£7.50
£17.00
Line-by-line explanation
  1. Line 3The switch produces the value that's returned.
  2. Line 5Three countries share one case.
  3. Lines 6 to 9A block can do some work first; yield hands back its result.
  4. Line 1610 plus 3.5 times 2 is 17.00.
Example 3

The fall-through trap

Java
public class Main {
    public static void main(String[] args) {
        int level = 2;
        switch (level) {
            case 1:
                System.out.println("Bronze reward");
            case 2:
                System.out.println("Silver reward");
            case 3:
                System.out.println("Gold reward");
            default:
                System.out.println("Thanks for playing");
        }
    }
}
Output
Silver reward
Gold reward
Thanks for playing
Line-by-line explanation
  1. Line 7Execution starts at the matching case.
  2. Lines 8 to 12With no break, it carries on through every case below, so level 2 also gets the gold reward. Add break after each case, or use arrow cases.

Common Java switch Mistakes

Forgetting break in a classic switch

Don't
case "Mon":
    System.out.println("Work");
case "Sat":
    System.out.println("Rest");     // also runs for Mon
Do
case "Mon" -> System.out.println("Work");
case "Sat" -> System.out.println("Rest");

Using switch for ranges

Don't
switch (score) {
    case score >= 70 -> ...      // doesn't compile
}
Do
if (score >= 70) { ... } else if (score >= 50) { ... } else { ... }

Missing the semicolon after a switch expression

Don't
String size = switch (code) {
    case 1 -> "Small";
    default -> "Large";
}
Do
String size = switch (code) {
    case 1 -> "Small";
    default -> "Large";
};

Java switch in Real Projects

switch in real code

Command-line programs switch on the command the user typed, games switch on the current state such as MENU, PLAYING and PAUSED, and web servers switch on HTTP methods like GET and POST. Switch expressions over enums are popular in modern Java codebases because the compiler warns you when a new value isn't handled.

Java switch FAQ

Which types can a Java switch use?

Classic switches work with byte, short, char and int, their wrapper classes, String and enums. Without preview features, you can't switch on long, float, double or boolean constants. Java 21 pattern matching extends switch to any object type through type patterns.

Is switch faster than if-else in Java?

For many cases on an int or String, the compiler can turn a switch into a jump table or a hash lookup, which may be slightly faster than checking conditions one by one. In practice the difference rarely matters. Choose whichever reads more clearly.

What is the difference between a switch statement and a switch expression?

A switch statement runs code for the matching case and produces no value. A switch expression produces a value, which you assign or return, must cover every possible input, and ends with a semicolon when used in an assignment.

What does yield do in a Java switch?

yield hands back the value of a switch expression from a case that uses a block of several statements. It's needed in block cases and in classic colon-style cases inside a switch expression. A single-expression arrow case, such as case 2 -> 28;, doesn't need it.

Can a switch case match a range of values?

Not directly: a case label must be a constant, so there's no case 1..10. Use if/else if for ranges, or in Java 21 use a type pattern with a when guard, such as case Integer n when n >= 90 -> "A";.

Java switch Exercises

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

Fill in the blankseasy

Complete the classic case so the code doesn't fall through to the next case.

case "red":
    System.out.println("Stop");
    ;
Predict the outputeasy

What does this print?

int n = 3;
String word = switch (n) {
    case 1 -> "one";
    case 2, 3 -> "a few";
    default -> "many";
};
System.out.println(word);
Predict the outputmedium

What does this print?

int x = 1;
switch (x) {
    case 1: System.out.print("A");
    case 2: System.out.print("B"); break;
    case 3: System.out.print("C");
}
Multiple choicemedium

What does yield do?

Multiple choicehard

Which type can't be used in a switch?

Java switch Quiz

5 questions to check what you learned.

  1. What runs when no case matches?

    • The first case
    • Nothing ever
    • The default case
    • The last case
  2. Do arrow cases (case x ->) fall through?

    • No, they never fall through
    • Yes, always
    • Only without default
    • Only for strings
  3. Why must a switch expression usually have a default?

    • Style rules
    • It must produce a value for every possible input
    • Java runs default first
    • To add a break
  4. How do you match "Sat" and "Sun" in one arrow case?

    • case "Sat" || "Sun" ->
    • case ["Sat", "Sun"] ->
    • case "Sat" and "Sun" ->
    • case "Sat", "Sun" ->
  5. Which situation suits if-else better than switch?

    • Choosing a menu option by number
    • Handling the days of the week
    • Giving grades based on score ranges like 70 and above
    • Reacting to an enum value