The yield statement is used in a switch expression to exit a case and return a value. This value becomes the result of the entire switch expression. The expression after yield must not be void.
In a switch expression, use yield to return a value. return exits a method, not a switch case.
String result = switch (day) {
case 1 -> "Sunday";
case 2 -> {
yield "Monday"; // Correct
// return "Monday"; ❌ Invalid here
}
default -> "Other";
};
class Test {
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public int calculate(Day d) {
return switch (d) {
case SATURDAY, SUNDAY -> 0;
default -> {
int remainingWorkDays = 5 - d.ordinal();
yield remainingWorkDays;
}
};
}
}
| Feature yield (Java 13+) | break (Traditional switch) |
|---|---|
| Used in switch expressions | Switch statements |
| Purpose: Returns a value from a case block | Exits the case block |
| Returns A value (used in expressions) | Nothing |
| Example yield “Weekday”; | break; |
| Multi-line case required when using a block {} | Optional, but used to prevent fall-through |