Java 7: Strings in Switch Statement
Before Java 7, the switch statement was quite limited in the types of data it could evaluate. It only supported primitive integral types like byte, short, char, int, and their corresponding wrapper classes, as well as enum types. If developers needed to branch logic based on a String value, they had to rely on a tedious and often messy chain of if-else if statements using the String.equals() method.
Java 7 broke this limitation by introducing the ability to use String objects directly within the switch statement. This enhancement made the code significantly cleaner, more readable, and easier to maintain. Instead of writing boilerplate if-else structures, developers could now clearly map string inputs to specific execution branches using the familiar case labels.
Under the hood, the Java compiler optimizes a switch statement on a String by utilizing the String.hashCode() method. It first creates a switch on the hash code of the string, and then, because hash collisions can occur, it performs an equals() check within the matching case. This two-step process ensures that the string switch is evaluated efficiently, generally performing better than an equivalent if-else chain for a large number of branches.
When using strings in switch statements, it is crucial to handle null values before the switch block. If the string expression evaluated by the switch is null, a NullPointerException will be thrown, just as it would if you called a method on a null reference. Also, the case labels must be exact string literals or compile-time constants.
How it Works
You simply pass a String variable into the switch(expression) block. The case labels must be string literals enclosed in double quotes. The evaluation is case-sensitive, meaning "Apple" and "apple" will match different cases. Always remember to include a default case to handle unexpected string inputs.
Java Example
Scenario 1: Basic String Switch
public class StringSwitchExample1 {
public static void main(String[] args) {
String day = "Tuesday";
switch (day) {
case "Monday":
System.out.println("Start of the work week.");
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
System.out.println("Midweek days.");
break;
case "Friday":
System.out.println("Almost weekend!");
break;
case "Saturday":
case "Sunday":
System.out.println("Weekend!");
break;
default:
System.out.println("Invalid day.");
}
}
}
Output
Midweek days.
Scenario 2: Case Sensitivity
public class StringSwitchExample2 {
public static void main(String[] args) {
String command = "START";
switch (command) {
case "start":
System.out.println("Starting in lowercase...");
break;
case "START":
System.out.println("Starting in UPPERCASE...");
break;
default:
System.out.println("Command not recognized.");
}
}
}
Output
Starting in UPPERCASE...
Scenario 3: Handling Null Values Safely
public class StringSwitchExample3 {
public static void processAction(String action) {
if (action == null) {
System.out.println("Action cannot be null.");
return;
}
switch (action) {
case "save":
System.out.println("Saving file...");
break;
case "delete":
System.out.println("Deleting file...");
break;
default:
System.out.println("Unknown action.");
}
}
public static void main(String[] args) {
processAction(null);
processAction("save");
}
}
Output
Action cannot be null.
Saving file...
Key Points
- Improves code readability compared to long
if-else ifchains. - Switch string evaluation is strictly case-sensitive.
- The compiler optimizes execution using
hashCode()andequals(). - Passing a
nullstring to the switch statement throws aNullPointerException.
Comments