Java Switch
When you need to compare a single value against many fixed options, a long chain of else if statements gets noisy fast. Java's switch statement is a cleaner way to branch on the value of one variable. This lesson covers the classic switch, the fall-through behaviour of break, and the modern arrow syntax introduced in recent Java versions.
Why use switch
A switch statement evaluates one expression once and then jumps to the case label that matches its value. It works with int and other whole-number types, char, String, and enums. Compared to a stack of else if branches, a switch makes it obvious that every branch is comparing the same variable.
A classic switch statement
public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Another day");
}
}
}
// Output:
// WednesdayThe role of break and default
Each case ends with a break so that execution leaves the switch once a match is handled. Without break, Java falls through and keeps running the code in the following cases until it hits a break or the end of the switch. The optional default label runs when no case matches, acting like the else of a switch.
- case - a label to match the switch value against.
- break - stops the switch so control does not fall into the next case.
- default - the catch-all branch when nothing else matches.
- Fall-through - the behaviour where a missing break lets execution continue into the next case.
Intentional fall-through
Sometimes several values should be treated the same way. Stacking case labels with no code between them lets them share one block. Here weekdays and weekend days each map to a single message.
Grouping cases together
public class Main {
public static void main(String[] args) {
int day = 6;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Invalid day");
}
}
}
// Output:
// WeekendThe modern arrow syntax
Modern Java (14 and later) offers a switch that uses arrows instead of colons. Each arrow branch runs only its own code with no fall-through, so you never need break. A switch can even be used as an expression that returns a value, which pairs nicely with the var keyword.
Switch expression with arrows
public class Main {
public static void main(String[] args) {
int day = 3;
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Another day";
};
System.out.println(name);
}
}
// Output:
// WednesdayExercise: Java Switch
What happens when a case in a traditional switch statement has no break?