文章目录
- 43. Java `switch` 语句 `null` 选择器变量
- `null` 选择器变量
- 示例:处理 `null` 选择器变量
- 程序输出:
- 解释 📖
- 为什么需要这样做? 🤔
- 更进一步:使用 `Optional` 避免 `null` 检查
- 示例:使用 `Optional` 包装选择器变量
- 程序输出:
- 解释 📚
- 总结 📝
43. Java switch 语句 null 选择器变量
null 选择器变量
在 Java 中,switch 语句的选择器变量(selector variable)可以是任何类型的对象,包括 String 类型或自定义类的对象。然而,如果选择器变量的值是 null,并且你在 switch 语句中直接使用它,就会抛出 NullPointerException 异常。
因此,在使用 switch 语句时,应该确保选择器变量不会为 null,或者在使用之前进行检查,以避免运行时错误。✅
示例:处理 null 选择器变量
class NullSelectorDemo {
public static void main(String[] args) {
String month = null; // 假设选择器变量为 null
// 检查 null,防止 NullPointerException
if (month == null) {
System.out.println("Month cannot be null");
} else {
switch (month) {
case "January":
System.out.println("First month of the year");
break;
case "February":
System.out.println("Second month of the year");
break;
// 其他月份的 case
default:
System.out.println("Unknown month");
}
}
}
}
程序输出:
Month cannot be null
解释 📖
- 在这个示例中,我们首先检查了
month是否为null。如果为null,则打印一条提示信息。 - 只有在
month不是null时,才会执行switch语句。
为什么需要这样做? 🤔
switch 语句在处理 null 时会抛出 NullPointerException,如果选择器变量是 null,程序会在运行时崩溃。通过在执行 switch 语句之前对选择器变量进行 null 检查,我们可以有效避免这个异常。💡
更进一步:使用 Optional 避免 null 检查
为了更优雅地避免处理 null,Java 提供了 Optional 类,它是一种容器类型,专门用于表示可能为空的值。使用 Optional,你可以显式地避免进行繁琐的 null 检查。
示例:使用 Optional 包装选择器变量
import java.util.Optional;
class OptionalSwitchDemo {
public static void main(String[] args) {
Optional<String> month = Optional.ofNullable(null); // Optional 中的值可以为 null
// 使用 ifPresentOrElse 进行处理,避免 null 的情况
month.ifPresentOrElse(m -> {
switch (m) {
case "January":
System.out.println("First month of the year");
break;
case "February":
System.out.println("Second month of the year");
break;
default:
System.out.println("Unknown month");
}
}, () -> System.out.println("Month cannot be null"));
}
}
程序输出:
Month cannot be null
解释 📚
- 我们使用
Optional.ofNullable()来包装可能为空的month变量。 - 使用
ifPresentOrElse()方法来分别处理month存在和为空的情况。若month不为null,则执行switch语句;如果为null,则执行第二个参数中的处理方法。
总结 📝
switch语句的选择器变量为null时,会抛出NullPointerException,因此,在使用switch语句时,确保选择器变量不为null是一种很好的实践。if语句:通过在使用switch前先检查变量是否为null,我们可以避免NullPointerException。Optional:Java 的Optional类提供了一种更优雅的方式来避免null值带来的问题,避免了传统的繁琐null检查。
通过这些方法,我们可以提高程序的健壮性,避免因 null 导致的运行时错误,从而让代码更安全、易于维护。🎯



















