java 7 起 switch 支持 string,枚举天然支持 switch,核心做法是确保分支常量不可变且无 null 值。string 比较依赖 equals() 并缓存 hashcode,枚举则利用实例引用相等性。若传入 null 或重复常量,会直接抛出异常或编译报错。

switch 对 String 的处理机制与空值风险
当使用字符串作为 switch 表达式时,编译器会生成基于 equals() 和 hashCode() 的比较逻辑。如果传入的字符串变量为 null,程序会在运行时抛出 NullPointerException,因为底层无法对空对象调用方法。

public class StringSwitchDemo {
public static void main(String[] args) {
String status = "active";
// 安全处理:先判空
if (status == null) {
System.out.println("Status is null");
} else {
switch (status) {
case "active":
System.out.println("User is active");
break;
case "inactive":
System.out.println("User is inactive");
break;
default:
System.out.println("Unknown status");
}
}
}
}
上述代码中,status 被显式检查为 null。在 switch 块内部,case "active": 匹配成功时执行打印并跳出。若 status 为 null,则进入 if 分支,避免了 NPE。预期输出为 User is active(当输入为 "active" 时)。
立即学习“Java免费学习笔记(深入)”;
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
枚举类型在 switch 中的优势与语法简化
枚举类型在 switch 中使用时,不需要在 case 后加引号,直接使用枚举常量名。由于枚举实例是单例的,JVM 通过引用相等性(==)进行比较,效率高于 String 的 equals 调用。此外,枚举提供了类型安全的约束,防止非法值传入。

public enum Role {
ADMIN, USER, GUEST
}
public class EnumSwitchDemo {
public static void main(String[] args) {
Role currentRole = Role.ADMIN;
switch (currentRole) {
case ADMIN:
System.out.println("Full access granted");
break;
case USER:
System.out.println("Standard access granted");
break;
case GUEST:
System.out.println("Limited access granted");
break;
}
}
}
该程序中,currentRole 被赋值为 Role.ADMIN。switch 语句直接匹配 case ADMIN:,无需引号。预期输出为 Full access granted。若尝试传入非枚举类型的值,编译器将报错,确保了类型安全。
当 switch 表达式为 null 时会发生什么
如果 switch 表达式本身为 null,无论是 String 还是其他对象,都会立即抛出 NullPointerException。对于枚举,由于枚举常量不能为 null(除非显式定义一个 null 常量,但这通常不被推荐),因此枚举 switch 相对更安全,但仍需确保表达式变量不为 null。对于 String,必须在使用前进行 null 检查。

















