switch(expr1)中,expr1是一个整数表达式。
因此 expr1支持的数据类型有五种
他们分别是:
byte、char、short、int、枚举。
long、String 都不能作用于swtich。
注明:以上是JDK1.6以前的版本。
------------------------------------------------------------------------------
JDK7新特性: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;
}
本文介绍了 Java 中 switch 语句的发展历程,从 JDK 1.6 的 byte、char、short、int 和枚举类型支持,到 JDK 7 引入了对 String 类型的支持,并提供了示例代码。

376

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



