1、Strings in switch Statements
In the JDK 7 release, you can use a String object in the expression of aswitch statement:
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;
}
The switch statement compares the String object in its expression with the expressions associated with eachcase label as if it were using theString.equals method; consequently, the comparison ofString objects inswitch statements is case sensitive. The Java compiler generates generally more efficient bytecode fromswitch statements that useString objects than from chainedif-then-else statements.
参考:http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html
2、和一连串的if-else-then想比,使用switch来计较String,Java编译器会生成更加有效的字节码
本文介绍了如何在Java 7中利用String类型作为switch语句的条件表达式,相比于传统的if-else语句,这种方法使得Java编译器能够生成更高效的字节码。文章还提供了一个具体的例子,展示了如何根据不同字符串值执行不同的操作。

被折叠的 条评论
为什么被折叠?



