Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 201 ยท Control Flow

switch Statements and Expressions

Master Java switch - classic case and break, fall-through, arrow labels, switch expressions with yield, strings, enums, null handling and exhaustiveness.

When one value decides between many fixed options, such as a menu choice, a day of the week, an HTTP method or an order status, a long if/else if chain becomes repetitive: the same variable is compared again and again. switch states the idea directly: "look at this value and jump to the matching case".

Java's switch has two generations. The classic form, inherited from C, uses case ...: labels and break, and it is famous for the fall-through bug. The modern form (standard since Java 14) uses arrow labels case ... ->, never falls through, and can be used as an expression that produces a value. You'll write the modern form in new code, but you'll read the classic one in existing code for years, so this lesson teaches both.

The classic switch statement

Java
switch (selector) {
    case VALUE_1:
        // statements
        break;
    case VALUE_2:
        // statements
        break;
    default:
        // when nothing else matched
}

Java evaluates the selector once, jumps to the case with an equal value (or to default if none matches), and runs statements from there until it hits break or the end of the switch.

Java A classic switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Cases 6 and 7 are stacked: case 6 has no statements of its own, so execution continues into case 7's code. Since Java 14 you can also write this as case 6, 7:.

default is optional and can go anywhere, though by convention it comes last. If no case matches and there is no default, a switch statement simply does nothing.

Fall-through: the classic bug

break is not decoration. Without it, execution falls through into the next case's statements, whether or not that case matches:

Java Forgetting break

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With level equal to 2, the program prints "Intermediate", then falls into "Advanced" and "Unknown level". Case labels are only entry points; they don't stop anything.

Occasionally fall-through is useful on purpose, for example when each level includes everything below it:

Java
switch (plan) {
    case "premium":
        features.add("priority support");
        // fall through
    case "standard":
        features.add("cloud backup");
        // fall through
    case "free":
        features.add("basic editor");
}

If you rely on it, mark it with a // fall through comment so readers (and linters) know it's intentional. In new code, though, the arrow form below is almost always clearer.

Variable scope in classic switches

All the cases of a classic switch share one block, so a variable declared in one case is visible (but not initialized) in the cases below it. Declaring the same name twice is a compile error:

Java
switch (command) {
    case "add":
        int amount = 5;      // scope: the whole switch block
        break;
    case "remove":
        int amount = 3;      // error: variable amount is already defined
        break;
}

Wrap each case's code in braces (case "add": { ... break; }) if it needs its own local variables, or use arrow labels, where each case has its own scope.

Modern switch with arrow labels

An arrow label case X -> runs exactly one thing: a single expression statement, a block in braces, or a throw. There is no fall-through and no break to forget. Several values can share one label, separated by commas:

Java Arrow labels with strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You can't mix : and -> labels in the same switch; pick one style per switch.

Switching on strings

A String selector compares with equals, so case matters: "get" doesn't match case "GET". That's why the example normalizes the input with toUpperCase() first. Under the hood the compiler uses hashCode() to jump close to the right case and then equals() to confirm, so a string switch is efficient even with many cases.

switch expressions

A switch expression produces a value, which you can assign, return or pass to a method. With arrow labels, the expression after -> is the result:

Java
String name = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    case 4 -> "Thursday";
    case 5 -> "Friday";
    case 6, 7 -> "Weekend";
    default -> "Not a day";
};   // note the semicolon: this is an assignment statement

Compare that to the classic version earlier: no repeated name =, no break, and no way to forget a branch. Two rules make switch expressions safe:

  1. Every path must produce a value. The switch must be exhaustive: it covers every possible selector value, which for int and String means you need a default. Leaving it out is a compile error, not a runtime surprise.
  2. When a case needs several statements, use a block and yield. yield gives the value of the block and leaves the switch.
Java switch expressions and yield

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

yield is a contextual keyword: it only has this meaning inside a switch expression, so older code that used yield as a variable name still compiles. Inside a switch expression you can't use return or break to jump out of it; yield and throw are the only ways a case can finish.

Switch expressions also work with the classic colon labels, using yield in each case:

Java
int points = switch (grade) {
    case 'A': yield 4;
    case 'B': yield 3;
    case 'C': yield 2;
    default: yield 0;
};

That form allows fall-through again, so prefer arrows.

Switching on enums

Enums are a perfect match for switch: a fixed set of named constants. Case labels use the bare constant name, without the enum type in front. A switch expression that lists every constant of an enum is exhaustive, so it needs no default:

Java Exhaustive switch on an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Leaving out default here is a feature. If someone later adds a RETURNED constant, both switch expressions stop compiling until they handle it. A default would silently swallow the new status. (If an enum changes after your code was compiled, the switch throws a MatchException at run time instead of misbehaving.)

What can you switch on?

Selector type Allowed?
int, short, byte, char and their wrappers Yes
String Yes (Java 7+)
Enum types Yes
Any reference type, with patterns Yes (Java 21+)
long, float, double, boolean No, use if (recent JDKs have a preview feature that adds primitive patterns)

Case labels for constants must be compile-time constants (literals, or final variables initialized with constants) and must not repeat. You can't write case x > 10 in a constant switch; ranges and conditions need if, or the pattern labels with when guards that you'll learn in Pattern Matching:

Java
String size = switch (shape) {
    case Circle c when c.radius() > 10 -> "large circle";
    case Circle c -> "circle";
    case Square s -> "square of side " + s.side();
    default -> "something else";
};

switch and null

A traditional switch on a String, enum or wrapper throws NullPointerException when the selector is null, before any case is considered. Since Java 21 you can handle null explicitly with case null, which can also be combined with default:

Java Handling null in a switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that default does not catch null. Only case null (or case null, default ->) does.

if or switch?

  • Use switch when one value is compared against several constants: menu choices, enum states, command names.
  • Use if for ranges, unrelated conditions or complex boolean logic.
  • Prefer a switch expression whenever the goal is to compute a value; let exhaustiveness checking work for you instead of adding a default to enum switches.
  • Prefer arrow labels in new code; keep classic labels for code bases that need to compile on very old Java versions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? int n = 1; switch (n) { case 1: IO.print("one "); case 2: IO.print("two "); break; case 3: IO.print("three"); }

    There is no break after case 1, so execution falls through into case 2, prints "two" and stops at its break.
  2. 2. What happens if a switch expression on an int has no default?

    A switch expression must produce a value for every possible input. For an int selector, only a default can cover all remaining values, so the compiler rejects it.
  3. 3. Inside a block of a switch expression, how do you produce the result?

    yield gives the block's value and leaves the switch expression. return and break can't be used to leave a switch expression.
  4. 4. Given String s = null;, what does switch (s) { case "a" -> IO.println("a"); default -> IO.println("other"); } do?

    default does not match null. Without a case null label, a null selector throws NullPointerException.
  5. 5. Why can it be better to leave out default in a switch expression over an enum?

    When every constant is listed, the switch is exhaustive without default. Adding a constant then makes it non-exhaustive, so the code stops compiling until you add a case.

Summary

  • A classic switch jumps to the matching case and runs until break; forgetting break causes fall-through into the next cases.
  • All cases of a classic switch share one scope; use braces or arrow labels for per-case variables.
  • Arrow labels (case A, B ->) run one expression, block or throw and never fall through.
  • A switch expression produces a value, must be exhaustive, and uses yield to return a value from a block.
  • You can switch on int-like types, their wrappers, String, enums and (with patterns) any object, but not long, float, double or boolean.
  • A null selector throws NullPointerException unless you add case null; default never matches null.

Next: while and do-while Loops, where you'll repeat code for as long as a condition stays true.