前言
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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论