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 abreak is encountered.
1. Examples of enum types:
1 Public classTestswitch {2 3 Static enumE {4 A, B, C, D5 }6 7 Public Static voidMain (String args[]) {8E e =e.b;9 Switch(e) {Ten CaseA: OneSystem.out.println ("A"); A Break; - CaseB: -System.out.println ("B"); the Break; - CaseC: -System.out.println ("C"); - Break; + CaseD: -System.out.println ("D"); + Break; A default: atSYSTEM.OUT.PRINTLN (0); - } - } -}
2. The use of break statements: output the number of days of a month in a given year
int year = 2018;
intMonth = 8;intDay = 0;Switch(month) { Case1: Case3: Case5: Case7: Case8: Case10: Case12: Day= 31; Break; Case2: Day= 28; Break; Case4: Case6: Case9: Case11: Day= 30; Break;} System.out.println (day);
The switch statement for the Java basic syntax