JDK21中switch的具体使用
作者:考虑考虑
JDK21允许switch传入null,避免空指针异常,提升灵活性,本文主就来介绍一下JDK21中switch的具体使用,感兴趣的可以了解一下
前言
jdk21
支持了新的switch属性
switch使用
在JDK21
之前,switch
不支持传入null,否则直接抛异常
public class SwitchDemo { public static void main(String[] args) { Integer a = null; switch (a) { case 1: System.out.println(1); case 2: { a = a + 1; System.out.println(a); } default: { System.out.println("默认值=========="); } } } }
输出结果为
jdk21
之后,支持传入null
public class SwitchDemo { public static void main(String[] args) { Integer a = null; switch (a) { case 1 -> System.out.println(12); case 2 -> { a = a + 1; System.out.println(a); } case null -> { System.out.println("数据为空"); } default -> { System.out.println("默认值=========="); } } } }
总结
用高版本的jdk有这不同的语法糖,这个看技术选型
到此这篇关于JDK21中switch的具体使用的文章就介绍到这了,更多相关JDK21 switch内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!