java14后switch 两种新用法

java14后switch 两种新用法

小赵
2022-05-21 / 0 评论 / 33 阅读 / 正在检测是否收录...

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);
0

Deprecated: strtolower(): Passing null to parameter #1 ($string) of type string is deprecated in /www/WEB/www.xzhao.vip/var/Widget/Archive.php on line 1035

评论 (0)

取消