switch的一些特性

1.正常形式

代码
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
switch (a) {
    case 1: {
        System.out.println("一");
        break;
    }
    case 2: {
        System.out.println("二");
        break;
    }
    case 3: {
        System.out.println("三");
        break;
    }
    default : {
        System.out.println("无");
        break;
    }

2.精简(java12 新特性)

代码
1
2
3
4
5
6
switch (a) {
    case 1 -> System.out.println("一");
    case 2 -> System.out.println("二");
    case 3 -> System.out.println("三");
    default -> System.out.println("无");
}

3.枚举

代码
1
2
3
4
5
switch (a) {
    case 1,2,3,4,5 -> System.out.println("工作日");
    case 6,7 -> System.out.println("休息日");
    default -> System.out.println("没有这个星期");
}