Switch Statement
A switch statement selects a branch from a set of exact values. It is often clearer than an else if chain that repeatedly compares one variable.
The traditional colon form continues into later cases unless break stops it. That behavior is called fall-through.
Print a day name
public class Main {
public static void main(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
}
}
Output:
Tuesday
The value 2 matches case 2, so the program prints Tuesday. A value without a matching case reaches default.
A switch can also match String values. Each case compares the text, the same way equals would:
public class Main {
public static void main(String[] args) {
String size = "M";
switch (size) {
case "S":
System.out.println("Small");
break;
case "M":
System.out.println("Medium");
break;
default:
System.out.println("Unknown size");
}
}
}
Output:
Medium
Accidental fall-through is a common bug. Modern arrow cases avoid it, as the next lesson shows.
Complete a simple calculator with switch.