Switch with String and Enum Types
You'll learn how to use switch statements with String values and enum constants, expanding your control flow options beyond primitive numeric types.
Beyond Primitive Types
You already know that switch works with int, byte, short, and char. Java also allows you to switch on String values (since Java 7) and enum constants, making your code more readable when dealing with text-based or categorical choices.
Switching on Strings
String fruit = "apple";
switch (fruit) {
case "apple":
System.out.println("Red or green");
break;
case "banana":
System.out.println("Yellow");
break;
case "orange":
System.out.println("Orange color");
break;
default:
System.out.println("Unknown fruit");
}
Important: String comparisons in switch are case-sensitive. "Apple" won't match "apple".
Switching on Enums
Enums are perfect for switch because they represent a fixed set of constants:
enum Day { MONDAY, TUESDAY, WEDNESDAY }
Day today = Day.MONDAY;
switch (today) {
case MONDAY:
System.out.println("Start of work week");
break;
case TUESDAY:
case WEDNESDAY:
System.out.println("Midweek");
break;
default:
System.out.println("Other day");
}
Notice you write case MONDAY, not case Day.MONDAY — the enum type is already known.
Null Handling Warning
Critical: If your String or enum variable is null, the switch will throw a NullPointerException at runtime. Always ensure your variable isn't null before switching, or handle it explicitly with an if check first.
if (fruit != null) {
switch (fruit) { /* safe */ }
}
Key Takeaway: switch statements work with String and enum types, offering readable alternatives to long if-else chains, but you must guard against null values to avoid runtime exceptions.