File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ title: Java14新特性:Switch表达式
2
+ tags:
3
+ - java14
4
+ categories:
5
+ - Dev
6
+ - Java
7
+ date: 2020-03-18 14:36:00
8
+ cover: true
9
+
10
+ ---
11
+
12
+ ![ ] ( http://q6pznk9ej.bkt.clouddn.com/img%20%288%29.jpeg )
13
+ <!-- more -->
14
+ > Java 14正式发布switch表达式特性。在之前的两个 Java 版本Java12,Java13,switch特性只是预览版。
15
+ 新的switch表达式有助于避免一些bug,因为它的表达和组合方式更容易编写。
16
+
17
+ switch新的表达式有两个特点:
18
+ * 支持箭头表达式返回。
19
+ * 支持yied和return返回值。
20
+ ## Java 14之前switch语法
21
+ ```
22
+ switch (season) {
23
+ case SPRING:
24
+ case AUTUMN:
25
+ System.out.println("温暖");
26
+ break;
27
+ case SUMMER:
28
+ System.out.println("炎热");
29
+ break;
30
+ case WINTER:
31
+ System.out.println("寒冷");
32
+ break;
33
+ }
34
+ ```
35
+
36
+ ## Java 14 switch表达式
37
+ ```
38
+ switch (season) {
39
+ case SPRING, AUTUMN -> System.out.println("温暖");
40
+ case SUMMER -> System.out.println("炎热");
41
+ case WINTER -> System.out.println("寒冷");
42
+ }
43
+ ```
44
+ Java 14的switch表达式使用箭头表达时,不需要我们在每一个case后都加上break,减少我们出错的机会。
45
+
46
+ ## Java14之前switch语法返回值
47
+ ```
48
+ String temperature ="";
49
+ switch (season) {
50
+ case SPRING:
51
+ case AUTUMN:
52
+ temperature = "温暖";
53
+ break;
54
+ case SUMMER:
55
+ temperature = "炎热";
56
+ break;
57
+ case WINTER:
58
+ temperature = "寒冷";
59
+ break;
60
+ default:
61
+ temperature = "忽冷忽热";
62
+ }
63
+ ```
64
+ 它不支持返回值,需要通过一个中间变量来返回。
65
+
66
+ ## Java14 switch表达式返回值
67
+ ```
68
+ String temperature = switch (season) {
69
+ case SPRING, AUTUMN -> "温暖";
70
+ case SUMMER -> "炎热";
71
+ case WINTER -> "寒冷";
72
+ }
73
+ ```
You can’t perform that action at this time.
0 commit comments