JDK23支持switch传入long类型

203 阅读1分钟

前言

JDK23以前版本,不支持使用Long或者long类型传入,但是JDK23支持该类型了,但是只是预览属性

switch使用

JDK23以往版本中,switch这么写,会报错

public class Test {

    public static void main(String[] args) {
        Long a = 1L;
        switch (a) {
            case 1L:
                System.out.println(1);
                break;
            case 2L:
                System.out.println(2);
                break;
        }
    }
}

会报

image.png

但是JDK23版本支持long类型了

public class LongDemo {

    public static void main(String[] args) {
        long a = 1L;
        switch (a) {
            case 1L -> System.out.println(1);
            case 2L -> System.out.println(2);
            default -> System.out.println(3);

        }
    }
}

输出

image.png

备注该功能必须开启预览属性

总结

JDK23中,JEP 455 的预览特性中,switch 全面支持所有原始类型,包括 byteshortcharintlongfloatdoubleboolean