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

Explain modern switch block #2893

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions exercises/concept/football-match-reports/.docs/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,62 @@ switch (direction) {
break;
}
```

## Modern Switch Statements

The switch statement was improved in the latest Java versions.

- The `break` keyword is not needed and the arrow operator is used instead of the semicolon.
- Multiple case values can be provided in a single case statement.

```java
String direction = getDirection();
switch (direction) {
case "left" -> goLeft();
case "right" -> goRight();
case "top", "bottom" -> goStraight();
default -> markTime();
}
```

The first LTS (Long Term Support) version that had these improvements was Java 17, released on September, 2021.

Other improvement is that the case values can be any object.

## Switch Expressions

Going even further, the switch block is now an expression, meaning it returns a value.

```java
return switch (day) { // switch expression
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Week day";
case "Saturday", "Sunday" -> "Weekend";
default -> "Unknown";
};
```

instead of using a switch statement:

```java
String day = "";
switch (day) { // switch statement
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> day = "Week day";
case "Saturday", "Sunday" -> day = "Weekend";
default-> day = "Unknown";
};
```

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

```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.