In Java 17, the switch statement received several enhancements, including improvements to switch expressions. These enhancements aim to make switch statements more powerful, flexible, and concise. Here's an overview of how switch works:
1. Traditional switch Statement
Java's traditional switch statement has been in the language since its inception. It allows you to compare the value of a variable against multiple possible constant values, executing different blocks of code based on the match.
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
// More cases...
default:
dayName = "Invalid day";
break;
}
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
// More cases...
default:
dayName = "Invalid day";
break;
}
2. Switch Expressions
Switch expressions were introduced as a preview feature in Java 12 and finalized in Java 14. In Java 17, switch expressions received further enhancements.int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
// More cases...
default -> "Invalid day";
};
- The arrow ("->") syntax is used to indicate the value to be returned for each case.
- The "switch" expression evaluates to a value, which can be assigned directly to a variable.
3. Enhancements in Java 17
Java 17 introduced several enhancements to switch expressions:- Multiple Labels Per Case
You can now have multiple labels in a single "case" label, separated by comma (",").
int num = 2;
String result = switch (num) {
case 1, 2 -> "One or Two";
case 3 -> "Three";
default -> "Other";
};
String result = switch (num) {
case 1, 2 -> "One or Two";
case 3 -> "Three";
default -> "Other";
};
- Relaxed Scoping for Switch Variables
In Java 17, the scope of variables declared in the expression of a switch statement has been relaxed. This means that the variables declared in the expression can now be used in subsequent case blocks without requiring extra curly braces.
int num = 2;
String result = switch (num) {
case 1 -> {
int x = 10;
yield "One";
}
case 2 -> {
yield "Two";
}
default -> "Other";
};
String result = switch (num) {
case 1 -> {
int x = 10;
yield "One";
}
case 2 -> {
yield "Two";
}
default -> "Other";
};
These enhancements make switch expressions more versatile and reduce boilerplate code, leading to more readable and concise code.
Nenhum comentário:
Postar um comentário