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
之前添加适当的空值检查。