在JDK 7发布版本中, 可以在switch语句的表达式中使用String对象:
public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
String typeOfDay;
switch (dayOfWeekArg) {
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
return typeOfDay;
}
switch
语句比较表达式中的 String
对象和每个 case 标签关联的表达式,就好像它是在使用String.equals
方法一样;因此,switch语句中 String
对象的比较是大小写敏感的。相比于链式的if-then-else语句,Java编译器通常会从使用String
对象的switch
语句中生成更高效的字节码。
本文翻译自Oracle官方文档http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html,如有不正确的地方,敬请指正,谢谢!