Switch Statement in Java
The switch statement in Java provides a way to execute different code blocks based on the value of an expression. It's often used as an alternative to long if-else-if chains when you need to compare a single variable against multiple constant values.
Basic Syntax
switch (expression) {
case value1:
// code to execute if expression == value1
break;
case value2:
// code to execute if expression == value2
break;
// more cases...
default:
// code to execute if none of the above cases match
}Key Features
-
Expression Types: Can be:
- Primitive types:
byte,short,char,int - Wrapper classes:
Byte,Short,Character,Integer -
String(since Java 7) -
enumtypes
- Primitive types:
Case Values: Must be constants or literals, and must match the type of the switch expression.
-
Break Statement:
- Terminates the switch block
- Without
break, execution will "fall through" to the next case
-
Default Case:
- Optional
- Executes when no other cases match
Examples
Basic Example with int
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
// ... other cases ...
default:
dayName = "Invalid day";
}
System.out.println(dayName); // Output: WednesdayString Example
String fruit = "Apple";
switch (fruit) {
case "Apple":
System.out.println("It's an apple");
break;
case "Banana":
System.out.println("It's a banana");
break;
default:
System.out.println("Unknown fruit");
}Fall-Through Example (tbds)
int month = 2;
int year = 2020;
int numDays = 0;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
numDays = 31;
break;
case 4: case 6: case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month");
}Enhanced Switch (Java 12+) tbds
Java 12 introduced a more concise form of switch expression:
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
// ... other cases ...
default -> "Invalid day";
};Yield (Java 13+) tbds
For more complex cases, you can use yield:
String season = switch (month) {
case 12, 1, 2 -> "Winter";
case 3, 4, 5 -> {
System.out.println("Spring months");
yield "Spring";
}
case 6, 7, 8 -> "Summer";
case 9, 10, 11 -> "Autumn";
default -> "Invalid month";
};Best Practices
- Always include a
defaultcase unless you're certain all possible values are covered - Use
breakstatements to prevent fall-through unless intentional - Consider using enhanced switch expressions for cleaner code (Java 12+)
- For complex conditions,
if-elsemight be more appropriate thanswitch
Switch vs. If-Else in Java: When to Use Each
Key Differences
| Feature |
switch Statement |
if-else Chain |
|---|---|---|
| Purpose | Compare one value against multiple constants | Evaluate multiple boolean conditions |
| Readability | Clean for many constant comparisons | Better for complex conditions |
| Performance | Often optimized to jump table (faster) | Evaluates each condition sequentially |
| Expression | Works with limited types (int, String, enum) | Works with any boolean expression |
| Fall-through | Cases fall through without break
|
No fall-through behavior |
When to Use Switch (tbds)
// Good for discrete values
int dayOfWeek = 3;
String dayType;
switch (dayOfWeek) {
case 1: case 2: case 3: case 4: case 5:
dayType = "Weekday";
break;
case 6: case 7:
dayType = "Weekend";
break;
default:
dayType = "Invalid day";
}Best for:
- Comparing a single variable against multiple constant values
- More than 3-4 conditions for the same variable
- Situations where readability improves with case labels
- Scenarios where performance matters (jump table optimization)
When to Use If-Else
// Better for complex conditions
int temperature = 25;
String weatherAdvice;
if (temperature > 30 && humidity > 80) {
weatherAdvice = "Heat warning! Stay indoors.";
} else if (temperature < 0 || windChill < -10) {
weatherAdvice = "Extreme cold warning!";
} else if (temperature >= 20 && temperature <= 25 && !isRaining) {
weatherAdvice = "Perfect weather for outdoor activities!";
} else {
weatherAdvice = "Normal weather conditions.";
}Best for:
- Range-based conditions (
x > 10 && x < 20) - Multiple variables in conditions
- Complex boolean expressions
- Non-constant comparisons
- Fewer than 3-4 conditions
Modern Java Switch Expressions (Java 14+) tbds
// Combines benefits of both with cleaner syntax
String dayType = switch (dayOfWeek) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> throw new IllegalArgumentException("Invalid day: " + dayOfWeek);
};Conversion Examples
If-Else to Switch
// Before (if-else)
if (grade == 'A') {
System.out.println("Excellent");
} else if (grade == 'B') {
System.out.println("Good");
} else if (grade == 'C') {
System.out.println("Average");
} else {
System.out.println("Fail");
}
// After (switch)
switch (grade) {
case 'A': System.out.println("Excellent"); break;
case 'B': System.out.println("Good"); break;
case 'C': System.out.println("Average"); break;
default: System.out.println("Fail");
}Switch to If-Else
// Before (switch)
switch (score) {
case 100: reward = "Gold"; break;
case 80: reward = "Silver"; break;
case 60: reward = "Bronze"; break;
default: reward = "None";
}
// After (if-else)
if (score == 100) {
reward = "Gold";
} else if (score == 80) {
reward = "Silver";
} else if (score == 60) {
reward = "Bronze";
} else {
reward = "None";
}Performance Considerations
- For many cases (5+),
switchis generally faster due to potential jump table optimization - For few cases (2-3),
if-elsemay be equally efficient - Modern JVMs optimize both constructs well, so prefer readability unless profiling shows a bottleneck