Switch statement

suggest change

The switch statement is Java’s multi-way branch statement. It is used to take the place of long if-else if-else chains, and make them more readable. However, unlike if statements, one may not use inequalities; each value must be concretely defined.

There are three critical components to the switch statement:

With the exception of continue, it is possible to use any statement which would cause the abrupt completion of a statement. This includes:

In the example below, a typical switch statement is written with four possible cases, including default.

Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
switch (i) {
    case 0:
        System.out.println("i is zero");
        break;
    case 1:
        System.out.println("i is one");
        break;
    case 2:
        System.out.println("i is two");
        break;
    default:
        System.out.println("i is less than zero or greater than two");
}

By omitting break or any statement which would an abrupt completion, we can leverage what are known as “fall-through” cases, which evaluate against several values. This can be used to create ranges for a value to be successful against, but is still not as flexible as inequalities.

Scanner scan = new Scanner(System.in);
int foo = scan.nextInt();
switch(foo) {
    case 1:
        System.out.println("I'm equal or greater than one");
    case 2:
    case 3:    
        System.out.println("I'm one, two, or three");
        break;
    default:
        System.out.println("I'm not either one, two, or three");
}

In case of foo == 1 the output will be:

I'm equal or greater than one
I'm one, two, or three

In case of foo == 3 the output will be:

I'm one, two, or three

The switch statement can also be used with enums.

enum Option {
    BLUE_PILL,
    RED_PILL
}

public void takeOne(Option option) {
    switch(option) {
        case BLUE_PILL:
            System.out.println("Story ends, wake up, believe whatever you want.");
            break;
        case RED_PILL:
            System.out.println("I show you how deep the rabbit hole goes.");
            break;
            
    }
}

The switch statement can also be used with Strings.

public void rhymingGame(String phrase) {
    switch (phrase) {
        case "apples and pears":
            System.out.println("Stairs");
            break;
        case "lorry":
            System.out.println("truck");
            break;
        default:
            System.out.println("Don't know any more");
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents