switch能传String类型的参数
Java 7版本的变化
在Java中,switch语句可以接受String类型的参数,但这是从Java 7版本开始引入的新特性。在Java 7之前,switch语句只能接受整数类型的参数(int、byte、short或char)。
代码实例
String fruit = "apple";
switch (fruit) {
case "apple":
System.out.println("It's an apple.");
break;
case "banana":
System.out.println("It's a banana.");
break;
case "orange":
System.out.println("It's an orange.");
break;
default:
System.out.println("Unknown fruit.");
}
使用时的注意事项
使用switch语句时,String类型的参数必须是非空的。
如果fruit为null,则会引发NullPointerException。
因此,在使用switch语句之前,请确保参数不为null,或者在使用switch之前添加适当的空值检查。
Java7开始,switch语句可以接受String类型参数,如示例所示用于条件判断。使用时注意参数不应为null,否则会导致NullPointerException。建议在使用前进行空值检查。

479

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



