switch Statement
The switch statement in Java is a multi-branch decision-making control structure. It is used when a variable or expression needs to be compared against multiple constant values, providing a cleaner and more readable alternative to long if-else ladders. This topic is important for interviews and real-world logic implementation.
What Is the switch Statement?
- Evaluates an expression once
- Matches it against multiple case values
- Executes the matching case block
- Uses break to prevent fall-through
Basic Syntax
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Simple Example
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;
default:
System.out.println("Invalid day");
}
Supported Data Types in switch
Java switch supports:
- byte, short, char, int
- enum
- String (Java 7+)
Not supported:
- ❌ long
- ❌ float, double
- ❌ boolean
Role of break Statement
- Terminates the switch block
- Prevents fall-through execution
Example Without break
int x = 1;
switch (x) {
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
}
Output:
One
Two
default Case
- Executes when no case matches
- Optional but recommended
- Can be placed anywhere, but best at the end
default:
System.out.println("Invalid option");
switch with String
String browser = "Chrome";
switch (browser) {
case "Chrome":
System.out.println("Launching Chrome");
break;
case "Firefox":
System.out.println("Launching Firefox");
break;
default:
System.out.println("Unsupported browser");
}
switch with enum (Best Practice)
enum Day { MON, TUE, WED }
Day day = Day.MON;
switch (day) {
case MON:
System.out.println("Monday");
break;
case TUE:
System.out.println("Tuesday");
break;
default:
System.out.println("Other day");
}
switch vs if-else
| Feature | switch | if-else |
|---|---|---|
| Readability | Better for multiple options | Better for complex conditions |
| Data Types | Limited | Any boolean expression |
| Performance | Faster in some cases | Depends on logic |
| Conditions | Equality-based | Range & logical checks |
Common Beginner Mistakes
- Forgetting break
- Using unsupported data types
- Expecting range conditions in switch
- Missing default case
Interview-Ready Answers
Short Answer
The switch statement is used to execute different blocks of code based on the value of an expression.
Detailed Answer
In Java, the switch statement evaluates an expression and executes the matching case block. It provides a cleaner alternative to long if-else ladders and supports data types like int, char, enum, and String.
Key Takeaway
The switch statement simplifies multi-value decision logic. It improves readability and maintainability when handling multiple discrete values.