Java switch Statement
In this page:
Basic switch Statement
A switch statement compares one variable's value against a list of possible cases in sequence, which reads more cleanly than a long chain of else-if blocks all testing the exact same variable.
Example: Basic 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;
}
}
}
Login to try C/C++/Java/PHP code in the editor
The Importance of break
Without a break at the end of a matching case, execution 'falls through' into the next case's code even if its own condition wasn't checked -- this is a frequent source of bugs for developers new to switch statements.
Example: The Importance of break
public class Main {
public static void main(String[] args) {
int day = 1;
switch (day) {
case 1: System.out.println("Monday");
case 2: System.out.println("Tuesday"); break; // falls through from case 1
case 3: System.out.println("Wednesday"); break;
}
}
}
Login to try C/C++/Java/PHP code in the editor
Using the default Case
default acts as the switch equivalent of else, running only when none of the explicit case values match the switch's expression -- it's good practice to always include one to handle unexpected values gracefully.
Example: Using the default Case
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"); break;
}
}
}
Login to try C/C++/Java/PHP code in the editor
Grouping Switch Cases
Stacking multiple case labels back to back with no code between them, like case 1: case 2: doSomething(); break;, makes both 1 and 2 trigger the same shared block instead of duplicating that code twice.
Example: Grouping Switch Cases
public class Main {
public static void main(String[] args) {
int num = 2;
switch (num) {
case 1:
case 2:
System.out.println("One or two");
break;
default:
System.out.println("Something else");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Switch on String
Since Java 7, you can switch on a String value directly (switch (day) { case "Monday": ... }), which is often more readable than converting the string to a numeric code first just to use a switch.
Example: Switch on String
public class Main {
public static void main(String[] args) {
String day = "Monday";
switch (day) {
case "Monday": System.out.println("Start of week"); break;
case "Friday": System.out.println("Almost weekend"); break;
default: System.out.println("Midweek");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: