Java21 如何使用switch case

发布时间:2024年01月12日

1. Java8 和 Java21

Java8 引入字符串和枚举

Java21 可以返回值, yield关键字, switch 表达式, 模式匹配, null值处理

2. 代码案例

1. Java8

 public static void java8() {
        String day = "tuesday";
        switch (day) {
            case "monday":
                System.out.println("work");
                break;
            case "tuesday":
                System.out.println("work");
                break;
            case "saturday":
                System.out.println("day off");
                break;
            case "sunday":
                System.out.println("day off");
                break;
        }
         //枚举值monday,tuesday,wednesday,thursday,friday,saturday,sunday;
        Days days = Days.saturday;
        switch (days) {
            case Days.monday:
                System.out.println("work");
                break;
            case Days.tuesday:
                System.out.println("work");
                break;
            case Days.saturday:
                System.out.println("day off");
                break;
            case Days.sunday:
                System.out.println("day off");
                break;
        }
    }

运行结果

20240112010117

2. Java21

 public static String java21() {
        //null 处理
        var name = switch (getName()) {
            case "" -> "";
            case "1" -> "num";
            case null -> "null";
            default -> "unknown";
        };
        System.out.println(name);
        //模式匹配
        Object o = 1;
        Object a = switch (o) {
            case Integer i -> 1 + i;
            case String s -> "1" + s;
            default -> o.toString();
        };
        System.out.println(a);
        //yield , 表达式
        String day = "sunday";
        return switch (day) {
            case "monday", "tuesday" -> "work";
            case "saturday", "sunday" -> {
                System.out.println("day off");
                yield "work";
            }
            default -> "unknown";
        };

    }

    static String getName() {
        return null;
    }

运行结果

![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/1670ab90491845e7837694481e89eab7.png
java21运行结果

文章来源:https://blog.csdn.net/Zhengzhanjie/article/details/135542089
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。