Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

switch

Picks a branch by value; as an expression it returns a result.

Available since: Java 1.0

Syntax

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

Examples

A switch expression with arrows — no break and no fall-through:

void main() {
    String day = "SAT";
    String type = switch (day) {
        case "SAT", "SUN" -> "weekend";
        case "MON", "TUE", "WED", "THU", "FRI" -> "weekday";
        default -> "unknown";
    };
    IO.println(type);
}

Output:

weekend

Type patterns and a when guard (Java 21):

String describe(Object o) {
    return switch (o) {
        case null -> "null";
        case Integer i when i < 0 -> "negative int";
        case Integer i -> "int " + i;
        case String s -> "string of length " + s.length();
        default -> "something else";
    };
}
 
void main() {
    IO.println(describe(-5));
    IO.println(describe(8));
    IO.println(describe("hi"));
    IO.println(describe(null));
}

Output:

negative int
int 8
string of length 2
null

The old colon form: without break execution falls into the next case:

void main() {
    int level = 1;
    switch (level) {
        case 1:
            IO.println("level 1");
        case 2:
            IO.println("level 2");
            break;
        default:
            IO.println("other");
    }
}

Output:

level 1
level 2

Notes

switch works with int and smaller integers, char, String, enum and (since Java 21) any object through type patterns. A switch expression must cover every case: strings and numbers need default, while for an enum or a sealed hierarchy it can be skipped if all values are listed.

See also

  • yield — Returns a value from a block inside a switch expression.
  • if / else — Runs a block of code only if a condition is true.
  • enum — Declares an enum — a type with a fixed set of values.
  • sealed / permits — Restricts which classes may extend a class or implement an interface.
  • instanceof — Checks whether an object is an instance of a type and binds a variable of that type.

Related recipes

In the tutorial

  • switch — The switch statement in Java: arrow labels, several values per case, switch expressions that return a value, yield and the classic form with break.

Thanks for reading!

Donate to the site — we work hard for you.