Skip to content

Commit

Permalink
Add patterns to switch explanation (#2899)
Browse files Browse the repository at this point in the history
Co-authored-by: Kah Goh <[email protected]>
  • Loading branch information
josealonso and kahgoh authored Jan 7, 2025
1 parent a3415b9 commit d53f6ab
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions concepts/switch-statement/.meta/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
"Azumix"
],
"contributors": [
"josealonso"
]
}
16 changes: 16 additions & 0 deletions concepts/switch-statement/about.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,23 @@ Starting with Java 14 (available as a preview before in Java 12 and 13) it is po

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

In addition, a feature called `Guarded Patterns` was added in Java 21, which allows you to do checks in the case label itself.

```java
String dayOfMonth = getDayOfMonth();
String day = "";
return switch (day) {
case "Tuesday" when dayOfMonth == 13 -> "Forbidden day!!";
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Week day";
case "Saturday", "Sunday" -> "Weekend";
default -> "Unknown";
};
```

You can find more information on the switch expression on Java 21 [here][switch-on-Java-21]

[yield-keyword]: https://www.codejava.net/java-core/the-java-language/yield-keyword-in-java
[switch1]: https://www.vojtechruzicka.com/java-enhanced-switch/
[switch2]: https://howtodoinjava.com/java14/switch-expressions/
[oracle-doc]: https://docs.oracle.com/en/java/javase/13/language/switch-expressions.html
[switch-on-Java-21]: https://blog.adamgamboa.dev/switch-expression-on-java-21/#3-guarded-pattern
4 changes: 4 additions & 0 deletions concepts/switch-statement/links.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,9 @@
{
"url": "https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html",
"description": "oracle-doc"
},
{
"url": "https://blog.adamgamboa.dev/switch-expression-on-java-21/#3-guarded-pattern",
"description": "switch-on-Java-21"
}
]

0 comments on commit d53f6ab

Please sign in to comment.