Java Tutorial · Control Flow · Lesson 14 of 37

Java Switch

Classic switch statements and modern switch expressions with arrows and patterns.

Switch expressions (Java 14+)

Modern Java uses arrow cases. There's no fall-through, several labels can share a case, and switch can return a value:

Example 1
public class Main {
    public static void main(String[] args) {
        String day = "SAT";
        String type = switch (day) {
            case "SAT", "SUN" -> "Weekend";
            case "MON", "TUE", "WED", "THU", "FRI" -> "Weekday";
            default -> "Unknown";
        };
        System.out.println(type);
        int month = 2;
        int days = switch (month) {
            case 2 -> 28;
            case 4, 6, 9, 11 -> 30;
            default -> 31;
        };
        System.out.println(days);
    }
}

Output

Weekend
28

Run this on your computer — see “Get Started” for setup.

Classic switch statement

Older code uses case X: with break. Forgetting break makes execution fall through to the next case:

Example 2
public class Main {
    public static void main(String[] args) {
        int level = 2;
        switch (level) {
            case 1:
                System.out.println("Beginner");
                break;
            case 2:
                System.out.println("Intermediate");
                // no break: falls through!
            case 3:
                System.out.println("Advanced");
                break;
            default:
                System.out.println("Unknown");
        }
    }
}

Output

Intermediate
Advanced

Run this on your computer — see “Get Started” for setup.

Pattern matching (Java 21)

switch can match on types and destructure records, with when guards:

Example 3
public class Main {
    public static void main(String[] args) {
        Object[] values = {42, "hello", 3.5, new Point(0, 0), new Point(2, 3)};
        for (Object v : values) {
            String description = switch (v) {
                case Integer i when i > 40 -> "big int " + i;
                case Integer i -> "int " + i;
                case String s -> "string of length " + s.length();
                case Point(int x, int y) when x == 0 && y == 0 -> "the origin";
                case Point(int x, int y) -> "point at " + x + "," + y;
                default -> "something else: " + v;
            };
            System.out.println(description);
        }
    }

    record Point(int x, int y) {}
}

Output

big int 42
string of length 5
something else: 3.5
the origin
point at 2,3

Run this on your computer — see “Get Started” for setup.

Test yourself

Do arrow-style (->) switch cases fall through?

  1. Yes
  2. No
  3. Only without default
Show answer

Answer: No