Java Switch Statement
What is a switch Statement?
A switch statement is another decision-making tool, like if-else. It’s useful when you want to check a variable against many values. Instead of writing many if-else if-else, switch can be cleaner and easier to read.
Basic Syntax
switch (variable) {
case value1:
// code to run if variable == value1
break;
case value2:
// code to run if variable == value2
break;
...
default:
// code to run if none of the cases match
}Key points
variable can be int, char, String, or enum.
Each case checks a possible value of the variable.
break stops the program from running all the next cases.
default runs if no case matches (like else in if-else).
Example – Day of the Week
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;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}Wednesday
How switch Works
Java checks the variable against all the cases from top to bottom.
If it finds a match, it runs that case.
break prevents it from running all the remaining cases (called "fall-through").
If no match is found, the default block runs.
Example – Multiple Cases Together
Sometimes you want the same code for multiple values:
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
case 'C':
System.out.println("You passed!");
break;
case 'D':
case 'F':
System.out.println("You failed!");
break;
default:
System.out.println("Invalid grade");
}You passed!
When to Use switch vs if-else
Use Case | Recommendation |
Few conditions, complex expressions | if-else |
Many fixed values of a single variable | switch |
Checking ranges (e.g., score > 50) | if-else |
Checking exact matches (e.g., day == 3) | switch |
Common Mistakes to Avoid
Quick Tips
Practice Exercises
Print the name of a month given its number (1–12).
Print whether a character is a vowel or consonant.
Create a simple calculator using switch (input operator +, -, *, /).
Convert a numeric score to grades using switch (e.g., 1 = A, 2 = B).