Switch(Expression) { case value : //statement break;//optional case value : //statement break;//optional //you can have any number of case statements default : //optional //statement }
The switch statement has the following rules:
- The variable type in a switch statement can be only a byte, short, int, or char.
- A switch statement can have more than one case statement. Each case is followed by a value and a colon to compare.
- The data type of the value in the case statement must be the same as the data type of the variable, and can only be constants or literal constants.
- When the value of a variable is equal to the value of the case statement, the statement after the case statement starts executing until the break statement appears and jumps out of the switch statement.
- The switch statement terminates when a break statement is encountered. The program jumps to the statement following the switch statement execution. The case statement does not have to contain a break statement. If no break statement appears, the program continues to execute the next case statement until a break statement appears.
- A switch statement can contain a default branch, which must be the last branch of a switch statement
- Default is executed when there is no case statement with the value equal to the value of the variable. The default branch does not require a break statement.
intI=5;Switch(i) {default: System.out.println ("Default part"); Case6: System.out.println ("First Case"); Case7: System.out.println ("Second Case");} System.out.println ("----");Switch(i) {default: System.out.println ("Default part"); Case5: System.out.println ("First Case"); Case7: System.out.println ("Second Case");}Test results:
Default part
First case
Second case
----
First case
Second case
--
From the result can be obtained: switch first to find all the case, once there is equal to from this case has been executed straight to see the end of the break. If there is no case to match, go to default, also until the break ends.
Switch-case Execution Order