The switch statement is a switch statement with a single condition and multiple branches. The syntax format is as follows:
switch (expression) {case constant value 1: statement 1; break; case constant value 2: statement 2; break; case constant value 3: statement 3; break;... case constant value n: statement n; break; default: Statement n+1;}
The value of "expression" in the switch statement can be of type byte, short, int, or char. "Constant value 1" to "constant value n" are also of type byte, short, int, or char, and they must be different from each other.
The switch statement first calculates the value of the expression. If the value of the expression is equal to the constant value after a certain case, the statements in the case are executed until the break statement is encountered. If a break statement is not used in a case, once the value of the expression is equal to the constant value behind the case, the program will not only execute the statements in the case, but also continue to execute statements in subsequent cases until the break statement is encountered. If the value of the expression in the switch statement is not equal to the constant value of any case, the statement following default is executed. The default in the switch statement is optional. If it does not exist, and the value of the expression in the switch statement is not equal to the constant value of any case, then the switch statement will not perform any processing.
The common feature of the if conditional branch statements we learned earlier is to choose to perform a branch operation based on one or more conditions, rather than choosing to perform multiple branch operations. In the switch statement, by rationally using the break statement, you can achieve the result of executing one branch or multiple branch operations based on a condition.
Example:
publicclassMain{publicstaticvoidmain(Stringargs[]){chargrade='B';switch(grade){case'A':System.out.println(excellent);break;case'B':System.out.println(good); break;case'C':System.out.println(passed);break;default:System.out.println(unknown);}}}
The running results are as follows:
good