Skip to content

Commit ea2b915

Browse files
authored
Small improvement about the enhanced switch block
Add example with guarded patterns and which LTS Java versions have these features.
1 parent bce1d70 commit ea2b915

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

concepts/switch-statement/about.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,23 @@ Starting with Java 14 (available as a preview before in Java 12 and 13) it is po
145145
However if you use the new `->` notation it must be followed by either: a single statement/expression, a `throw` statement or a `{}` block.
146146
No more confusion!
147147

148+
The first LTS (Long Term Support) version that had these improvements was Java 17, released on September, 2021.
149+
150+
In addition, a feature called `Guarded Patterns` was added, which allows you to do checks in the case label itself.
151+
152+
```java
153+
String dayOfMonth = getDayOfMonth();
154+
String day = "";
155+
return switch (day) {
156+
case "Tuesday" && dayOfMonth == 13 -> "Forbidden day!!";
157+
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Week day";
158+
case "Saturday", "Sunday" -> "Weekend";
159+
default -> "Unknown";
160+
};
161+
```
162+
163+
The first LTS (Long Term Support) version that had these improvements was Java 21, released on September, 2023.
164+
148165
You can find more information on enhanced switch [here][switch1], [here][switch2] and on the [oracle documentation][oracle-doc].
149166

150167
[yield-keyword]: https://www.codejava.net/java-core/the-java-language/yield-keyword-in-java

0 commit comments

Comments
 (0)