As your Java programs grow, you’ll often find yourself needing to choose between multiple values or actions. While if-else
chains can handle this, they can quickly become messy and repetitive. Enter the switch expression, a feature introduced in Java 14 that makes your code more concise and expressive.
What is a Switch Expression?
Traditionally, Java has had switch statements that allowed you to branch logic based on a value. However, they didn’t directly produce a result, you had to set a variable inside each case. With switch expressions, the switch itself returns a value, making it more flexible and elegant.
The general form looks like this:
Type result = switch (variable) {
case value1 -> expression1;
case value2 -> expression2;
...
default -> defaultExpression;
};
Notice the -> arrow syntax—it’s used instead of the old : style. And since it’s an expression, it can be directly assigned to a variable.
Example 1;
int seasonCode = 1;
String seasonName = switch (seasonCode) {
case 0 -> "Spring";
case 1 -> "Summer";
case 2 -> "Fall";
case 3 -> "Winter";
default -> "???";
};
System.out.println(seasonName);
If seasonCode is 1, seasonName becomes "Summer".
If none of the cases match, default provides a fallback value.
Final Thoughts
Switch expressions bring a fresh and elegant way to handle multiple choices in Java. They make your code shorter, cleaner, and less error-prone. Next time you’re tempted to write a long if-else chain or an old-style switch, try a switch expression instead, you’ll love the readability it adds
Top comments (0)