Skip to content

Commit d53f6ab

Browse files
josealonsokahgoh
andauthored
Add patterns to switch explanation (#2899)
Co-authored-by: Kah Goh <[email protected]>
1 parent a3415b9 commit d53f6ab

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

Diff for: concepts/switch-statement/.meta/config.json

+1
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,6 @@
44
"Azumix"
55
],
66
"contributors": [
7+
"josealonso"
78
]
89
}

Diff for: concepts/switch-statement/about.md

+16
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,23 @@ Starting with Java 14 (available as a preview before in Java 12 and 13) it is po
147147

148148
You can find more information on enhanced switch [here][switch1], [here][switch2] and on the [oracle documentation][oracle-doc].
149149

150+
In addition, a feature called `Guarded Patterns` was added in Java 21, 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" when 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+
You can find more information on the switch expression on Java 21 [here][switch-on-Java-21]
164+
150165
[yield-keyword]: https://www.codejava.net/java-core/the-java-language/yield-keyword-in-java
151166
[switch1]: https://www.vojtechruzicka.com/java-enhanced-switch/
152167
[switch2]: https://howtodoinjava.com/java14/switch-expressions/
153168
[oracle-doc]: https://docs.oracle.com/en/java/javase/13/language/switch-expressions.html
169+
[switch-on-Java-21]: https://blog.adamgamboa.dev/switch-expression-on-java-21/#3-guarded-pattern

Diff for: concepts/switch-statement/links.json

+4
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,9 @@
1414
{
1515
"url": "https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html",
1616
"description": "oracle-doc"
17+
},
18+
{
19+
"url": "https://blog.adamgamboa.dev/switch-expression-on-java-21/#3-guarded-pattern",
20+
"description": "switch-on-Java-21"
1721
}
1822
]

0 commit comments

Comments
 (0)