java14后多了两种新用法,方便理解,用代码案例描述,先用标准用法在用新用法
switch - > 用法
原始标准用法是

int dayOfWeek = 2;
switch (dayOfWeek) {
    case 1:
        System.out.println("星期一");
        break;
    case 2:
        System.out.println("星期二");
        break;
    case 3:
        System.out.println("星期三");
        break;
    case 4:
        System.out.println("星期四");
        break;
    case 5:
        System.out.println("星期五");
        break;
    case 6:
        System.out.println("星期六");
        break;
    default:
        System.out.println("星期日");
        break;
}

输出

星期二

新用法,代码如下

int dayOfWeek = 2;
switch (dayOfWeek) {
    case 1 -> System.out.println("星期一");
    case 2 -> System.out.println("星期二");
    case 3 -> System.out.println("星期三");
    case 4 -> System.out.println("星期四");
    case 5 -> System.out.println("星期五");
    case 6 -> System.out.println("星期六");
    default -> System.out.println("星期日");
}

switch yield 用法
标准用法代码:

String weekday = null;
int dayOfWeek = 2;
switch (dayOfWeek) {
    case 1:
        weekday = "星期一";
        break;
    case 2:
        weekday = "星期二";
        break;
    case 3:
        weekday = "星期三";
        break;
    case 4:
        weekday = "星期四";
        break;
    case 5:
        weekday = "星期五";
        break;
    case 6:
        weekday = "星期六";
        break;
    default:
        weekday = "星期日";
        break;
}
System.out.println(weekday);

新用法代码如下:

int dayOfWeek = 2;
String weekday = switch (dayOfWeek) {
    case 1:
        yield "星期一";
    case 2:
        yield "星期二";
    case 3:
        yield "星期三";
    case 4:
        yield "星期四";
    case 5:
        yield "星期五";
    case 6:
        yield "星期六";
    default:
        yield "星期日";
};
System.out.println(weekday);
最后修改:2022 年 05 月 21 日
如果觉得我的文章对你有用,请随意赞赏