Select statement --switch
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.
Execution Flow
demand
Code illustrates basic use of the switch
public class Demo07Switch { public static void main (String [] args) { // definition of variables, of the week is determined int NUM =. 6 ; // Switch statement to achieve select Switch (NUM) { Case . 1 : 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 ( "Data unreasonable" ); break ; // the last break statement can be omitted, but it is strongly recommended not to omit } } }
Results of the
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. "Which case match on a position from which to perform downward until it encounters a break or a whole until the end."
- In a switch statement, if the case does not write back break, will appear penetration phenomenon, which is not a value judgment in the case, run directly back, until it encounters a break, or the end of the whole switch. Because of penetrating case, therefore beginners when writing switch statement, you must write on the break.