Skip to content
Laviyx Learn

Try

Java course menu

Java switch Statements and switch Expressions (Arrow Syntax)

Learn the Java switch: the classic switch statement with case, break and fallthrough, switching on strings and enums, modern switch expressions with -> arrows (Java 14+), multiple labels per case, yield, and pattern matching for switch (Java 21).

Beginner13 min readUpdated
On this page

When one value is compared against many fixed options, a switch is clearer than a long else if chain. Java has the classic switch statement, and since Java 14 a much safer switch expression with arrow (->) syntax.

The classic switch statement#

Java
public class Main {
    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

Execution jumps to the matching case and runs until a break. default handles anything that matches no case.

Fallthrough#

Without break, execution falls through into the following cases:

Java
public class Main {
    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

Forgetting break is the classic switch bug, and a key reason the arrow syntax was added.

Switching on strings#

Unlike C and C++, Java can switch on a String (compared with equals):

Java
public class Main {
    public static void main(String[] args) {
        String command = "stop";

        switch (command) {
            case "start":
                System.out.println("Starting");
                break;
            case "stop":
                System.out.println("Stopping");
                break;
            default:
                System.out.println("Unknown command");
        }
    }
}
Output
Stopping

Java can switch on int (and smaller integer types), char, String, enums and their wrapper types; since Java 21, on any object type with patterns.

Arrow syntax: no fallthrough#

With case X ->, only the code for the matching case runs: no break needed and no fallthrough. Several labels can share one case:

Java
public class Main {
    public static void main(String[] args) {
        for (int day : new int[] {1, 6, 7, 9}) {
            switch (day) {
                case 1, 2, 3, 4, 5 -> System.out.println(day + ": weekday");
                case 6, 7 -> System.out.println(day + ": weekend");
                default -> System.out.println(day + ": invalid");
            }
        }
    }
}
Output
1: weekday
6: weekend
7: weekend
9: invalid

switch expressions: a switch that returns a value#

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

Java
public class Main {
    public static void main(String[] args) {
        char grade = 'B';

        String meaning = switch (grade) {
            case 'A' -> "Excellent";
            case 'B', 'C' -> "Good";
            case 'D' -> "Needs improvement";
            default -> "Invalid grade";
        };
        System.out.println(meaning);
    }
}
Output
Good

A switch expression must be exhaustive: every possible value must be covered, usually with default. The compiler checks this for you. Note the semicolon after the closing brace, because the whole switch is part of an assignment.

yield: several statements in one case#

When a case needs more than one statement, use a block and yield the result:

Java
public class Main {
    public static void main(String[] args) {
        int units = 250;
        String plan = "business";

        double bill = switch (plan) {
            case "home" -> units * 6.5;
            case "business" -> {
                double base = units * 8.0;
                yield base + 200;   // fixed charge
            }
            default -> throw new IllegalArgumentException("Unknown plan: " + plan);
        };
        System.out.println(bill);
    }
}
Output
2200.0

Switching on an enum#

Enums (see Records and Enums) are a perfect match for switch. In a switch expression over an enum that lists every constant, no default is needed, and the compiler reports an error if you later add a constant and forget to handle it:

Java
enum Light { RED, YELLOW, GREEN }

public class Main {
    public static void main(String[] args) {
        Light light = Light.YELLOW;
        String action = switch (light) {
            case RED -> "Stop";
            case YELLOW -> "Slow down";
            case GREEN -> "Go";
        };
        System.out.println(action);
    }
}
Output
Slow down

Inside the switch, write the constant name alone (RED), not Light.RED.

Pattern matching for switch (Java 21)#

Java 21 lets a switch test the type of an object, with an optional extra condition (when):

Java
public class Main {
    static String describe(Object value) {
        return switch (value) {
            case null -> "nothing";
            case Integer i when i > 100 -> "a big number";
            case Integer i -> "the number " + i;
            case String s -> "the text \"" + s + "\"";
            default -> "something else";
        };
    }

    public static void main(String[] args) {
        System.out.println(describe(7));
        System.out.println(describe(500));
        System.out.println(describe("hi"));
        System.out.println(describe(null));
        System.out.println(describe(2.5));
    }
}
Output
the number 7
a big number
the text "hi"
nothing
something else

You will see more of this in Modern Java Features.

Which form should I use?#

Prefer the arrow form for new code: it has no fallthrough, can be used as an expression, and the compiler checks exhaustiveness. Use the classic form only when you genuinely want fallthrough, or when working on older code.

Common mistakes#

Practice#

Practice exercise

Write a method daysInMonth(int month, boolean leapYear) using a switch expression, and print the result for months 2 (leap year), 4 and 12.

Show solution
Java
public class Months {
    static int daysInMonth(int month, boolean leapYear) {
        return switch (month) {
            case 1, 3, 5, 7, 8, 10, 12 -> 31;
            case 4, 6, 9, 11 -> 30;
            case 2 -> leapYear ? 29 : 28;
            default -> throw new IllegalArgumentException("Invalid month: " + month);
        };
    }

    public static void main(String[] args) {
        System.out.println(daysInMonth(2, true));
        System.out.println(daysInMonth(4, false));
        System.out.println(daysInMonth(12, false));
    }
}
Output
29
30
31

Key takeaway#

Finished this lesson?