Java: Switch Statement

Note: Not to be confused with switch expressions.

Arrow syntax (Java 12+)

switch (myInt) {
    case 1 -> System.out.println("One");
    case 2 -> {
        System.out.println("Two");
        System.out.println("No fall through");
    }
    default -> System.out.println("Something else");
}

No fall through.

Multiple statements require { ... }

Colon syntax

switch (myInt) {
    case 1:
        System.out.println("One");
        break;
    case 2:
        System.out.println("Two");
        System.out.println("Falling through");
    default:
        System.out.println("Something else");
}

Falls through if there's no break.

Multiple statements don't require { ... }

Multiple case constants

Both colon and arrow variants allow for multiple constants in each case:

switch (myInt) {
    case 1, 2, 3:
        System.out.println("One, two or three");
        break;
    default:
        System.out.println("Something else");
}

Can't mix colons and arrows

You can't have both cases with colon syntax and cases with arrow syntax in the same switch statement.

Fall through

Fall through is what happens when execution proceeds from the bottom of one case to the top of the subsequent case.

First case falls through. Output: "Hello World"

switch (1) {
    case 1:
        System.out.print("Hello ");
        // Fall through to next case
    case 2:
        System.out.println("World");
        break;
    default:
        System.out.println("Not executed");
}

Comments

Be the first to comment!