Skip to content

Commit e3353fd

Browse files
authored
Explained modern switch block
1 parent dc69bf0 commit e3353fd

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

exercises/concept/football-match-reports/.docs/introduction.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,63 @@ switch (direction) {
3232
break;
3333
}
3434
```
35+
36+
## Modern Switch Statements
37+
38+
The switch statement was improved in the latest Java versions.
39+
40+
- The `break` keyword is not needed and the arrow operator is used instead of the semicolon.
41+
- Multiple case values can be provided in a single case statement.
42+
43+
```java
44+
String direction = getDirection();
45+
switch (direction) {
46+
case "left" -> goLeft();
47+
case "right" -> goRight();
48+
case "top", "bottom" -> goStraight();
49+
default -> markTime();
50+
}
51+
```
52+
53+
The first LTS (Long Term Support) version that had these improvements was Java 17, released on September, 2021.
54+
55+
Other improvement is that the case values can be any object.
56+
57+
## Switch Expressions
58+
59+
Going even further, the switch block is now an expression, meaning it returns a value.
60+
61+
```java
62+
return switch (day) { // switch expression
63+
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Week day";
64+
case "Saturday", "Sunday" -> "Weekend";
65+
default -> "Unknown";
66+
};
67+
```
68+
69+
instead of using a switch statement:
70+
71+
```java
72+
String day = "";
73+
switch (day) { // switch statement
74+
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> day = "Week day";
75+
case "Saturday", "Sunday" -> day = "Weekend";
76+
default-> day = "Unknown";
77+
};
78+
```
79+
80+
In addition, a feature called `Guarded Patterns` was added, which allows you to do checks in the case label itself.
81+
82+
```java
83+
String dayOfMonth = getDayOfMonth();
84+
String day = "";
85+
return switch (day) {
86+
case "Tuesday" && dayOfMonth == 13 -> "Forbidden day!!";
87+
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Week day";
88+
case "Saturday", "Sunday" -> "Weekend";
89+
default -> "Unknown";
90+
};
91+
```
92+
93+
The first LTS (Long Term Support) version that had these improvements was Java 21, released on September, 2023.
94+

0 commit comments

Comments
 (0)