switch
When one variable is compared with a long list of values, an if ... else if chain gets bulky. switch writes such a choice more compactly: the value is checked against case labels, and the matching branch runs.
The arrow form
After switch you put the value to check in parentheses, and in the block — case labels with an arrow ->. Only the branch of the matching label runs; default runs if none of them matched:
void main() {
int day = 3;
switch (day) {
case 1 -> IO.println("Monday");
case 2 -> IO.println("Tuesday");
case 3 -> IO.println("Wednesday");
default -> IO.println("Another day");
}
}Output:
Wednesdayswitch works with whole numbers, characters, strings and enums (covered in the OOP chapter). Labels are checked for exact equality, so for ranges like "from 1 to 5" an if is more convenient.
Several values
One branch can handle several values at once — list them separated by commas:
void main() {
String day = "sat";
switch (day) {
case "mon", "tue", "wed", "thu", "fri" -> IO.println("Workday");
case "sat", "sun" -> IO.println("Weekend");
default -> IO.println("Unknown day");
}
}Output:
WeekendSwitch expressions
switch can not only perform actions but also return a value. Then it is called an expression, and the result is stored in a variable. It ends with a semicolon:
void main() {
int month = 7;
String season = switch (month) {
case 12, 1, 2 -> "Winter";
case 3, 4, 5 -> "Spring";
case 6, 7, 8 -> "Summer";
default -> "Autumn";
};
IO.println(season);
}Output:
SummerAn expression must return a value for any input, so default is required here.
yield
If a branch needs several actions, its code goes in curly braces, and the value is returned with the word yield:
void main() {
int items = 5;
double discount = switch (items) {
case 1, 2 -> 0;
default -> {
IO.println("Bulk discount");
yield 0.1;
}
};
IO.println(discount);
}Output:
Bulk discount
0.1The classic form
Older code uses switch with colons. There, after the matching label, all code runs until the word break — even the code of the following labels:
void main() {
int level = 2;
switch (level) {
case 1:
IO.println("Beginner");
break;
case 2:
IO.println("Experienced");
break;
default:
IO.println("Expert");
}
}Output:
ExperiencedIn new code use arrows: they are shorter and need no break.
Common mistake
In the classic form it is easy to forget break. Execution then "falls through" into the following branches:
void main() {
int level = 1;
switch (level) {
case 1:
IO.println("Beginner");
case 2:
IO.println("Experienced");
break;
default:
IO.println("Expert");
}
}Output:
Beginner
ExperiencedThe compiler does not warn about a missing break. The arrow form solves the problem: there is no fall-through in it.