The “switch” statement is a programming construct in Java and many other programming languages that allows a developer to branch the execution of code based on the value of a specific variable or expression. It is an alternative to using multiple “if-else” statements and can make the code more readable and organised when dealing with a large number of cases.
The “switch” statement has evolved significantly over the years as Java has continued to develop and improve. In the early versions of Java, the switch statement could only be used with primitive data types such as integers, characters and each case required the “case” keyword, a value, a colon, and a “break” statement to prevent falling through to the next case.
Since Java 5 you can use switch statement with enums and it still is considered a good practice since enums are final and limited.
Since Java 7 you can use switch statement with strings and it was probably one of the game-changers since you didn’t have to do mile-long chains of if-else statements anymore.
Since Java 12 switch statement changed into switch expression. The new syntax allowed developers to use arrow labels (->) instead of colons, eliminating the need for “break” statements and avoiding the fall-through behaviour. It also introduced the ability to have multiple case labels combined with a single statement, making the switch statement more concise and readable.
Since Java 13 you can actually return stuff that are executed within the switch expression with a “yield” keyword (or just the return object if a case if a one-liner):
public String getDayName(Day day) {
return switch (day) {
case MONDAY -> "Monday";
case TUESDAY -> "Tuesday";
case WEDNESDAY -> "Wednesday";
case THURSDAY -> "Thursday";
case FRIDAY -> "Friday";
case SATURDAY -> {
System.out.println("It's the weekend!");
yield "Saturday";
}
case SUNDAY -> {
System.out.println("It's the weekend!");
yield "Sunday";
}
};
}
NOTE: I don't really get the obsession some interviewers have about Java versions (unless the project IS working with a legacy code) but it's good to memorise them.
Why devs hate the switch statement?
Although since the beginnings of Java, the switch statement has gotten quite a makeover, many developers still dislike it for various reasons. Some of the biggest cons of using the switch statement (some were resolved since introducing the switch expression) include:
- Verbosity: The “switch” statement in Java can be quite verbose, especially when compared to other languages that have more concise pattern matching constructs. Each case in the switch statement needs a “case” keyword, a value, a colon, and a “break” statement, which can lead to more lines of code and reduced readability.
- Fall-through behaviour: One common source of bugs in switch statements is the fall-through behaviour, where the execution continues from one case to the next unless a “break” statement is explicitly used. This can lead to unintended consequences if a developer forgets to include a “break” statement, causing multiple cases to execute unintentionally.
- Limited expressions: Switch statements can only be used with certain types of expressions, such as integers, characters, enumerated types, and (since Java 7) strings. This limitation can be frustrating for developers who want to use more complex or custom data types in their switch statements.
- No support for complex conditions: Unlike “if-else” statements, switch statements in Java do not support complex conditions or boolean expressions. They only work with single values, which may not be suitable for scenarios where multiple conditions need to be checked.
- Maintainability: As the number of cases in a switch statement grows, the code can become more difficult to maintain. Adding, removing, or modifying cases may require careful attention to ensure that the “break” statements are properly placed and that fall-through behaviour is correctly managed.
- No expression support in cases: Java’s “switch” statement does not support expressions in the case labels, unlike some other languages. This limitation can make it difficult to write more flexible and expressive code when dealing with complex scenarios. In contrast, some other programming languages, like C# and Kotlin, support more advanced pattern matching and expressions in
switchstatements, providing greater flexibility and expressiveness in handling complex scenarios. - No scoped variables: In Java, when you declare a variable inside a switch block, its scope extends to the entire block, rather than being limited to the specific case it was declared in. To avoid these issues, you can use separate code blocks for each case by enclosing them in braces ({}), which will create a new scope for the variables declared within each case.
switch (x) {
case 1: {
int a = 10;
// ...
break;
}
case 2: {
int a = 20; // This 'a' is in a different scope and does not cause a conflict
// ...
break;
}
// ...
}
- Refactoring challenges: Switch statements can become a bottleneck when refactoring code. If you need to add or remove an enumeration value or any other type of value, you may have to update multiple switch statements throughout the codebase, which can be cumbersome and error-prone.
- Violation of the Open/Closed Principle: The “switch” statement often violates the Open/Closed Principle, a crucial object-oriented programming concept that states that software entities should be open for extension but closed for modification. When new cases are added, the switch statement must be modified, increasing the likelihood of introducing bugs.
What instead of Switch?
There are a couple alternatives to switch statements in Java:
- If-else chain: The most straightforward alternative to a switch statement is using an if-else chain. While it may not always be the most efficient or elegant solution, it can handle more complex conditions and expressions that switch statements cannot.
- Polymorphism: One of the most powerful alternatives to switch statements in object-oriented languages like Java is leveraging polymorphism. By encapsulating the behavior inside different subclasses and using inheritance and interfaces, you can achieve a more flexible and maintainable design. This approach follows the Open/Closed Principle and promotes code reusability (check the Strategy design pattern).
- Lookup tables and maps: In some cases, using a lookup table or a map can be a more efficient and concise alternative to a switch statement. This approach is especially useful when dealing with a large number of cases, and the primary operation is a simple lookup based on a key.
- Enhanced switch expressions (Java 12+): Starting from Java 12, enhanced switch expressions were introduced as a preview feature, which became a standard feature in Java 14. This new syntax allows developers to use more concise and readable code with the “->” operator and combined case labels, avoiding the fall-through behavior and some verbosity issues.
Switch statement in Java has improved, but still has downsides like verbosity, fall-through, limited expressions, and maintenance issues. Alternatives like if-else, polymorphism, and lookup tables exist. Java 12+ enhanced switch expressions also offer concise code. Ultimately, it’s up to the developer to choose the best approach based on the project’s needs and coding style.

/*
Until next time,
stay positive (like unsigned integer) and keep coding!
eMs
*/
