The Switch keyword is no stranger to most Java learners, and since the written and interview questions often ask for its usage, here's a simple summary:
- The types that can be used for switch judgments are: Byte, short, int, char (JDK1.6), and enumeration type, but after JDK1.7, the string type is added.
- The case statement writes less break, the compilation does not error, but it is executed all the time after the statement in the case condition is no longer judged until the default statement
- If you do not have a qualifying case to execute the code block under Default, default is not required, or you may not write
1 Packagecodeanal;2 3 Public classSwitchdemo {4 5 Public Static voidMain (string[] args) {6 stringtest ();7 breaktest ();8 defauttest ();9 }Ten One /* A * Default is not required or can not be written - * Output: case - */ the Private Static voiddefauttest () { - Charch = ' A '; - Switch(CH) { - CaseB: +SYSTEM.OUT.PRINTLN ("Case One"); - Break; + CaseA: ASYSTEM.OUT.PRINTLN ("Case"); at Break; - CaseC: -SYSTEM.OUT.PRINTLN ("Case Three"); - Break; - } - } in - /* to * Less break in case statement, compile without error + * However, the statements are executed after all case conditions and are no longer judged until the default statement - * The following code output: case Two the * Case Three * */ $ Private Static voidbreaktest () {Panax Notoginseng Charch = ' A '; - Switch(CH) { the CaseB: +SYSTEM.OUT.PRINTLN ("Case One"); A the CaseA: +SYSTEM.OUT.PRINTLN ("Case"); - $ CaseC: $SYSTEM.OUT.PRINTLN ("Case Three"); - default: - Break; the } - }Wuyi the /* - * switch is used to determine the type of string Wu * Output: It ' s ok! - */ About Private Static voidstringtest () { $String string =NewString ("Hello"); - Switch(string) { - Case"Hello": -System.out.println ("It ' s ok!"); A Break; + the default: -System.out.println ("error!"); $ Break; the } the } the}
Use of switch in Java