# java14新特性
# Switch表达式
传统 switch 是语句,不能直接返回值,必须通过 break 控制分支,且容易因漏写 break 导致 “穿透” 问题。
新 switch 是表达式,可以直接返回值,语法更简洁,还解决了穿透问题。
对比如下
public class SwitchDemo {
public static void main(String[] args) {
//旧版本
int a = 1;
switch (a) {
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
default:
System.out.println("default");
}
//新版本
switch (a){
case 1 -> System.out.println("1");
case 2 -> System.out.println("2");
default -> System.out.println("default");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
支持复杂的yield 关键字
public class SwitchYield {
//支持复杂的yield关键字
public static void main(String[] args) {
String grade="A";
int score=switch (grade){
case "A"->{
System.out.println("优秀");
yield 90;//直接返回值
}
case "B"-> 80;
default -> 0;
};
System.out.println(score);//90
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
支持代码块(多行逻辑)
Scanner scanner = new Scanner(System.in);
int day = scanner.nextInt();
switch (day){
case 1,2,3,4,5-> System.out.println("工作日");
case 6,7-> System.out.println("休息日");
default -> System.out.println("无效的输入");
}
1
2
3
4
5
6
7
2
3
4
5
6
7