Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Small improvement on the enhanced switch block explanation #2899

Merged
merged 8 commits into from
Jan 7, 2025
17 changes: 17 additions & 0 deletions concepts/switch-statement/about.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,23 @@ Starting with Java 14 (available as a preview before in Java 12 and 13) it is po
However if you use the new `->` notation it must be followed by either: a single statement/expression, a `throw` statement or a `{}` block.
No more confusion!

The first LTS (Long Term Support) version that had these improvements was Java 17, released on September, 2021.
josealonso marked this conversation as resolved.
Show resolved Hide resolved
josealonso marked this conversation as resolved.
Show resolved Hide resolved

In addition, a feature called `Guarded Patterns` was added, which allows you to do checks in the case label itself.
josealonso marked this conversation as resolved.
Show resolved Hide resolved

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

The first LTS (Long Term Support) version that had these improvements was Java 21, released on September, 2023.
josealonso marked this conversation as resolved.
Show resolved Hide resolved

You can find more information on enhanced switch [here][switch1], [here][switch2] and on the [oracle documentation][oracle-doc].
josealonso marked this conversation as resolved.
Show resolved Hide resolved

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