Switch expressions
Return a value from switch with arrow labels, no break statements and no fall-through.
Open this lesson in the learning hubKey points
- Arrow labels
case X -> ...never fall through, so there is nobreakto forget. - A switch expression produces a value, so you can assign or return it directly.
- Group labels with commas:
case 12, 1, 2 -> "winter";. - Need several statements? Use a block and
yieldthe result out of it. - Switch expressions must be exhaustive. Over an enum, cover every constant and skip
defaultso a new constant becomes a compile error. - Switch works on
int,char,Stringand enums — and on types via pattern matching in Java 21.
Example
public class Main {
enum Status { NEW, PAID, SHIPPED, CANCELLED }
static int daysToDeliver(Status s) {
return switch (s) {
case NEW, PAID -> 3;
case SHIPPED -> 1;
case CANCELLED -> {
System.out.println(" cancelled orders never ship");
yield -1;
}
};
}
public static void main(String[] args) {
for (Status s : Status.values()) {
System.out.println(s + " -> " + daysToDeliver(s) + " day(s)");
}
int month = 4;
String season = switch (month) {
case 12, 1, 2 -> "winter";
case 3, 4, 5 -> "spring";
case 6, 7, 8 -> "summer";
default -> "autumn";
};
System.out.println("month " + month + " is " + season);
}
}
Arrow switch returns a value, never falls through and needs no break.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.