A switch statement consists of a control expression and multiple case labels.
The types supported by the switch control expressions are byte, short, char, int, enum (Java 5), String (Java 7).
The Switch-case statement can be fully interoperable with the If-else statement, but generally, the Switch-case statement executes more efficiently.
Default is executed when the current switch cannot find a matching case. Default is not a must.
Once the case is matched, the subsequent program code is executed sequentially, regardless of whether the following case matches until a break is encountered.
Switch syntax format
Switch (expression) { case Condition 1: statement 1; Break ; Case Condition 2: statement 2; Break ;... default : statement;}
The branch statement evaluates the expression first, then matches the condition 1, condition 2 ... When the value of the expression matches the condition, the corresponding statement is executed and the default statement is executed if there is no response to the condition.
Byte
1 byteB1=12;2 Switch(B1) {3 Case1:4System.out.println ("Wrong");5 Break;6 7 Case2:8System.out.println ("Wrong2");9 Break;Ten One Case12: ASystem.out.println ("Right"); - Break; - the default: -System.out.println ("All Wrong"); -}
int:
1 intNum1=12;2 Switch(NUM1) {3 Case1:4System.out.println ("Wrong");5 Break;6 7 Case2:8System.out.println ("Wrong2");9 Break;Ten One Case12: ASystem.out.println ("Right"); - Break; - the default: -System.out.println ("All Wrong"); -}
Char
1 CharC1= ' a ';2 Switch(C1) {3 CaseA:4System.out.println ("A is right");5 Break;6 7 Case' B ':8System.out.println ("B is Right");9 Break;Ten One CaseC: ASystem.out.println ("C is right"); - Break; - default: the Break; -}
String
1String str1= "123";2 Switch(str1) {3 Case"111":4System.out.println ("111 is right");5 Break;6 7 Case"112":8System.out.println ("the".);9 Break;Ten One Case"123": ASystem.out.println ("123 is Right"); - Break; - default: theSystem.out.println ("No Right"); - Break; -}
Enum:
1 Static enume{2 a,b,c,d3 }4 Public Static voidMain (string[] args) {5E e=e.c;6 7 Switch(e) {8 CaseA:9System.out.println ("A is Right");Ten Break; One A CaseB: -System.out.println ("B is Right"); - Break; the - CaseC: -System.out.println ("C is Right"); - Break; + - CaseD: +System.out.println ("D is Right"); A Break; at default: -System.out.println ("No Right"); - Break; -}
The Java Basics switch