Java Enhanced Switch
Java's enhanced switch syntax makes small branching logic cleaner, especially when each case maps to one value.
The old switch style needed case, break, and more ceremony. The newer arrow form uses case value -> ..., which avoids accidental fallthrough.
Version Support
Enhanced switch became a standard feature in Java 14.
Before that:
- Java 12 introduced switch expressions as a preview feature.
- Java 13 continued the preview and refined
yield. - Java 14 finalized switch expressions and the enhanced switch syntax.
For normal coding practice, treat this as Java 14+.
Basic Example
Your idea:
switch (i) {
case '[' -> "yes [";
case ']' -> "yes ]";
default -> "none";
};
This is close, but if each branch produces a value, the switch should be used as an expression.
Clean version:
String result = switch (i) {
case '[' -> "yes [";
case ']' -> "yes ]";
default -> "none";
};
Now result receives the value from the matching case.
Why The Arrow Form Is Useful
Traditional switch statements can fall through:
switch (i) {
case '[':
result = "yes [";
break;
case ']':
result = "yes ]";
break;
default:
result = "none";
}
The arrow form does not fall through:
String result = switch (i) {
case '[' -> "yes [";
case ']' -> "yes ]";
default -> "none";
};
That makes it easier to read and harder to break by forgetting break.
Switch Statement vs Switch Expression
Enhanced switch can be used as a statement:
switch (i) {
case '[' -> System.out.println("yes [");
case ']' -> System.out.println("yes ]");
default -> System.out.println("none");
}
Here the switch performs an action.
It can also be used as an expression:
String result = switch (i) {
case '[' -> "yes [";
case ']' -> "yes ]";
default -> "none";
};
Here the switch returns a value.
Multiple Labels
You can combine labels when they produce the same result:
String bracketType = switch (i) {
case '[', ']' -> "square bracket";
case '(', ')' -> "round bracket";
case '{', '}' -> "curly bracket";
default -> "not a bracket";
};
This is useful in parsers, validation code, and character classification.
Block Cases With yield
If a case needs more than one line, use a block and yield the value:
String result = switch (i) {
case '[' -> {
String label = "yes [";
yield label;
}
case ']' -> "yes ]";
default -> "none";
};
yield returns a value from that switch case. It is not the same as return, which exits the whole method.
In A Method
For small mapping logic, a switch expression makes the method compact:
class Solution {
String label(char i) {
return switch (i) {
case '[' -> "yes [";
case ']' -> "yes ]";
default -> "none";
};
}
}
Takeaways
- Enhanced switch is standard from Java 14.
- Use
case value -> ...to avoid fallthrough. - Use switch as an expression when each branch produces a value.
- Use
yieldwhen a switch expression case needs a block. - For simple mappings, enhanced switch is cleaner than
if/elseor oldcaseplusbreak.