JDK21中的switch

404 阅读1分钟

前言

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("默认值==========");
            }
        }
    }
}

输出结果为

image.png 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有这不同的语法糖,这个看技术选型