also known switch statement select statement, the following format
The switch statement format:
Implementation process
- First, calculate the value of the expression
- Secondly, compare and order case, if there is a corresponding value, will execute the corresponding statement in the process of implementation, it encounters a break will end.
- Finally, if the case were all expressions and values do not match, it will execute the default statement body part, and the program ends off.
Code execution flow as shown below
Code Example
Package demo03_Switch; public class Demo01Switch { public static void main (String [] args) { // definition of variables, of the week is determined int WEEKDAY =. 1 ; // Switch statement to achieve select Switch (WEEKDAY) { Case . 1 : the System.out. println ( "Monday" ); BREAK ; Case 2 : System.out.println ( "Tuesday" ); BREAK ; Case 3 : System.out.println ( "Wednesday" ); BREAK ; Case 4 : System.out.println ( "Thursday" ); BREAK ; Case 5 : System.out.println ( "Friday" ); BREAK ; Case 6 : System. out.println ( "Saturday" ); BREAK ; Case 7 : System.out.println ( "Sunday" ); break; default: System.out.println("错误"); break; } } }
The result of code execution
Note the use of the switch statement:
- The latter case a plurality of values can not be repeated.
- Switch parentheses behind which only the following data types: basic data types: byte / short / char / int reference Data Type: String String, enum enum
- The switch statement format can be very flexible: before and after the order can be reversed, and break statement can also be omitted. case of penetration : in a switch statement, if the latter case is not writing break, will appear penetration phenomenon, which is not a value judgment in the case, run directly back, until it encounters a break, or the entire switch End. Because of penetrating case, you must write on the break.