Tech and Media Labs
This site uses cookies to improve the user experience.




Java Switch Statements

Jakob Jenkov
Last update: 2014-06-23

A switch statement works a bit like an if statement, except it can choose between more than two blocks of code to execute. Here is a simple example:

int amount = 9;

switch(amount) {
    case     0 : System.out.println("amount is  0"); break;
    case     5 : System.out.println("amount is  5"); break;
    case    10 : System.out.println("amount is 10"); break;
    default    : System.out.println("amount is something else");
}

This example first creates a variable named amount and assigns the value 9 to it.

Second, the example "switches" on the value of the amount variable. Inside the switch statement are 3 case statements and a default statement.

Each case statement compares the value of the amount variable with a constant value. If the amount variable value is equal to that constant value, the code after the colon (:) is executed. Notice the break keyword after each statement. If no break keyword was place here, the execution could continue down the rest of the case statements until a break is met, or the end of the switch statement is reached. The break keyword makes execution jump out of the switch statement.

The default statement is executed if no case statement matched the value of the amount variable. The default statement could also be executed if the case statements before it did not have a break command in the end. You don't need a default statement. It is optional.

Switch on byte, short, char, int, String, or enum's

As you have seen, the switch statement switches on a variable. Before Java 7 this variable has to be numeric and must be either a byte, short, char or int. From Java 7 the variable can also be a String It is also possible use a Java enum as switch variable.

Multiple case statements for same operation

In case you want the same operation executed for multiple case statements, you write it like this:

char key = '\t'

switch(amount) {
    case     ' '  :
    case     '\t' : System.out.println("white space char"); break;

    default       : System.out.println("amount is something else");
}

Notice how the first case statement does not have any operation after the colon. The result of this is, that execution just "drops" down to the operation of the next case statement ( and the next etc.) until a break is met. The next break statement is after the second case statement. That means, that for both the first and second case statement, the same operation is executed - that of the second case statement.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC