Introduction
The switch statement in Java is a control flow statement that allows you to execute one block of code out of multiple options based on the value of a variable. Since Java 7, switch supports String values, making it easier to compare text instead of using multiple if-else statements. This improves readability and simplifies code for handling multiple string conditions.
1. Basic Syntax of Switch with Strings
switch (variable) {
case "Value1":
// code block
break;
case "Value2":
// code block
break;
default:
// code block
}
Explanation:
variablemust be of typeString.- Each
casechecks for equality with the string value. breakprevents fall-through to the next case.defaultexecutes if no case matches.
2. Example: Switch with Strings
public class SwitchWithStrings {
public static void main(String[] args) {
String day = "Monday";
switch (day) {
case "Monday":
System.out.println("Start of the week!");
break;
case "Wednesday":
System.out.println("Midweek day!");
break;
case "Friday":
System.out.println("End of the workweek!");
break;
default:
System.out.println("Just another day");
}
}
}
Explanation:
dayis compared with eachcase."Monday"matches the first case, so it prints"Start of the week!".- Without
break, execution would continue to the next cases (fall-through). defaulthandles all unmatched values.
3. Benefits of Using Strings in Switch
- Improves readability: Cleaner than multiple
if-elsefor string comparisons. - Avoids repetitive code: No need to call
.equals()for each condition. - Efficient execution: Internally, Java uses a hash-based lookup for string switches.
Summary Table
| Feature | Description |
|---|---|
| Supported Type | String (since Java 7) |
| Case Matching | Exact match with the string value |
| Break Statement | Prevents fall-through |
| Default Case | Executes when no case matches |
| Benefit | Cleaner and more efficient than multiple if-else |
Conclusion
Using strings with the switch statement makes your Java code simpler, cleaner, and easier to maintain.
- Use
caseto match specific string values. - Always include a
defaultcase to handle unexpected values. - Remember to use
breakto prevent fall-through unless intentionally designing it.
Mastering switch with strings allows you to handle multiple text-based conditions efficiently in Java programs.