Switch

Switch

Switch statements express conditionals across many branches.

Here’s a basic switch.

public class Main {
    public static void main(String[] args) {
        int i = 2;
        System.out.print("Write " + i + " as ");
        switch (i) {
            case 1:
                System.out.println("one");
                break;
            case 2:
                System.out.println("two");
                break;
            case 3:
                System.out.println("three");
                break;
        }

        switch (java.time.DayOfWeek.from(java.time.LocalDate.now())) {
            case SATURDAY:
            case SUNDAY:
                System.out.println("It's the weekend");
                break;
            default:
                System.out.println("It's a weekday");
                break;
        }

        java.time.LocalTime t = java.time.LocalTime.now();
        switch (t.getHour()) {
            case int hour when hour < 12:
                System.out.println("It's before noon");
                break;
            default:
                System.out.println("It's after noon");
                break;
        }

        whatAmI(true);
        whatAmI(1);
        whatAmI("hey");
    }

    public static void whatAmI(Object o) {
        switch (o) {
            case Boolean b:
                System.out.println("I'm a bool");
                break;
            case Integer i:
                System.out.println("I'm an int");
                break;
            default:
                System.out.println("Don't know type " + o.getClass().getSimpleName());
                break;
        }
    }
}

You can use commas for multiple expressions in the same case statement. Here, we use the optional default case as well.

switch without an expression can express if/else logic. Non-constant case expressions can be used here.

A type switch compares types instead of values. This is useful for discovering the type of an interface value. In this example, the variable t will have the type corresponding to its clause.

$ java Main
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type String

Next example: Arrays.