Java Core: Control Flow - switch-case Statement
The switch-case statement is a multi-way decision-making statement in Java. It provides a more efficient and readable alternative to a series of if-else if-else statements when you need to compare a single variable against multiple possible values.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
...
case valueN:
// Code to execute if expression == valueN
break;
default:
// Code to execute if expression doesn't match any case
}
Explanation:
switch (expression): Theexpressionis evaluated. This expression must evaluate to an integer type (byte, short, char, int) or a String (Java 7 and later) or an enum type (Java 5 and later).case value1:: Eachcaselabel represents a specific value to compare against theexpression.// Code to execute...: If theexpressionmatches thevalue1, the code block associated with thatcaseis executed.break;: Thebreakstatement is crucial. It terminates theswitchstatement after a matchingcaseis executed. Withoutbreak, execution will "fall through" to the nextcase, even if it doesn't match.default:: Thedefaultcase is optional. It provides a block of code to execute if theexpressiondoesn't match any of thecasevalues. It's good practice to include adefaultcase to handle unexpected values.
Example 1: Using switch-case with int
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:
case 7: // Combining cases
System.out.println("Weekend");
break;
default:
System.out.println("Invalid day");
}
Output:
Wednesday
Example 2: Using switch-case with String (Java 7+)
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;
case "orange":
System.out.println("It's an orange!");
break;
default:
System.out.println("Unknown fruit");
}
Output:
It's an apple!
Example 3: Using switch-case with enum (Java 5+)
enum Color {
RED, GREEN, BLUE
}
public class EnumSwitch {
public static void main(String[] args) {
Color color = Color.GREEN;
switch (color) {
case RED:
System.out.println("The color is red.");
break;
case GREEN:
System.out.println("The color is green.");
break;
case BLUE:
System.out.println("The color is blue.");
break;
default:
System.out.println("Unknown color.");
}
}
}
Output:
The color is green.
Key Points:
breakis essential: Always includebreakstatements to prevent fall-through.defaultis optional but recommended: Handles unexpected values gracefully.- Data Types: The
expressionin theswitchstatement must be of a limited set of types:byte,short,char,int,String(Java 7+), or anenumtype (Java 5+). - Case Values:
casevalues must be constant expressions. You cannot use variables or expressions that are evaluated at runtime. - Combining Cases: You can combine multiple
caselabels if they should execute the same code. (See Example 1,case 6:andcase 7:) - Readability:
switch-casestatements often improve code readability compared to longif-else if-elsechains, especially when dealing with multiple possible values.
When to use switch-case:
- When you need to compare a single variable against a fixed set of possible values.
- When readability is important.
- When performance is critical (in some cases,
switch-casecan be more efficient than a longif-else if-elsechain).
When not to use switch-case:
- When you need to compare against ranges of values (use
if-else if-elseinstead). - When the conditions are complex and involve multiple variables.
- When the number of cases is very large and constantly changing (consider using a
Mapor other data structure).