Switch statement is a kind of efficient multi-path statement, can save a lot of complicated nested if judgment;
In Java 6 and before, the constants in a case statement can only be byte, char, short, and int (or the corresponding encapsulation class) or enumeration constants, and string is added to the Java 7 specification, after all it is a constant type;
Demo:
Public classcoinswitchstring { Public Static voidMain (string[] args) {Printday ("Sunday"); Printday ("Tuesday"); Printday ("Ten"); } Public Static voidPrintday (String dayOfWeek) {Switch(dayOfWeek) { Case"Sunday": System.out.println ("Sunday"); Break; Case"Monday": System.out.println ("Monday"); Break; Case"Tuesday": System.out.println ("Tuesday"); Break; Case"Wednesday": System.out.println ("Wednesday"); Break; Case"Thursday": System.out.println ("Thursday"); Break; Case"Friday": System.out.println ("Friday"); Break; Case"Saturday": System.out.println ("Saturday"); Break; default: System.out.println ("Error: '" + DayOfWeek + "is not a day of the week!"); } } }
Ran as Java application:
' Ten ' isn't a day of the week!
String in the 1.3.1 switch statement