public class StringSwitchExample {
public static void main(String[] args) {
String fruit = "apple";
switch (fruit) {
case "apple":
System.out.println("这是苹果");
break;
case "banana":
System.out.println("这是香蕉");
break;
case "orange":
System.out.println("这是橙子");
break;
default:
System.out.println("未知水果");
}
}
}
使用字符串作为switch条件时的注意事项:
- 字符串比较:
switch
语句中字符串比较是基于equals
方法,而不是==
。这意味着比较的是字符串的实际内容,而不是内存地址。
- 性能:在Java 7之前,
switch
语句只能处理整型(如byte
、short
、int
、char
及其包装类),使用字符串会增加性能开销,因为每次比较都要调用equals
方法。不过在Java 7及之后,switch
对字符串的处理进行了优化,性能影响相对较小,但仍需注意大数据量下的性能问题。
- 常量字符串:
case
标签后必须是常量字符串,不能是变量。
- 空指针:如果
switch
表达式的值为null
,会抛出NullPointerException
,所以在使用前要确保switch
表达式的值不为null
。