Java Switch
A switch statement picks a block by matching one value against a set of cases. Each case holds one value that can match.
A day number prints a weekday name
The value 2 matches the second case. The break line ends the switch right after that case prints.
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;
case 3:
System.out.println("Wednesday");
break;
}
}
}No break falls through
This switch is the same switch with the break lines removed. The run continues into the next case and prints its line too.
public class Main {
public static void main(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday");
case 3:
System.out.println("Wednesday");
}
}
}Default covers an unknown value
No case in this switch matches the value 9. The default case prints its line instead.
public class Main {
public static void main(String[] args) {
int day = 9;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Unknown day");
}
}
}Example
public class Main {
public static void main(String[] args) {
int option = 2;
switch (option) {
case 1:
System.out.println("View balance");
break;
case 2:
System.out.println("Make payment");
break;
case 3:
System.out.println("Exit");
break;
default:
System.out.println("Unknown option");
}
}
}Key points
- A switch compares one value against its cases.
- A case runs when its value matches the switch value.
- The break statement leaves the switch at once.
- Without break, the run falls into the next case.
- The default case runs when no case matches.
- Code after the switch runs once the switch ends.
In this example, option holds 2. The second case matches, so its line prints Make payment. The break line then leaves the switch, and no other case runs.
Note
The default case usually stands last, after every other case.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does break do inside a switch?