Document directory
New Java 7 feature: String in switch support
One of the new features added in Java 7 is the capability to switch onString.
With Java 6, or less
View plaincopy to clipboardprint?
- String color = "red ";
- If (color. Equals ("red ")){
- System. Out. println ("color is red ");
- } Else if (color. Equals ("green ")){
- System. Out. println ("color is green ");
- } Else {
- System. Out. println ("color not found ");
- }
With Java 7:
View plaincopy to clipboardprint?
- String color = "red ";
- Switch (color ){
- Case "red ":
- System. Out. println ("color is red ");
- Break;
- Case "green ":
- System. Out. println ("color is green ");
- Break;
- Default:
- System. Out. println ("color not found ");
- }
Conclusion
The switch statement when used withStringUsesequals()Method To compare the given expression to each value in the case statement and is therefore case-sensitive and will throwNullPointerExceptionIf the expression is null. It is a small but useful feature which not only helps us write more readable code but the compiler will likely generate more efficient bytecode as compared to if-then-elseStatement.
Sharethis
Related posts:
- Java 7: new feature-automatically close files and resources in try-catch-finally
- 2 ways to convert Java map to string
- 3 ways to serialize Java enums
- How to trim () No-break space (& #160;) when parsing HTML
- Installing Java 7 on Mac OS X
This article is from http://www.vineetmanohar.com/2011/03/new-java-7-feature-string-in-switch-support/