One of the new features added inJava 7is the capability to switch on aString
.
With Java 6, or less
view plaincopy to clipboardprint?
- Stringcolor=”red”;if(color.equals(“red”)){System.out.println(“ColorisRed”);}elseif(color.equals(“green”)){System.out.println(“ColorisGreen”);}else{System.out.println(“Colornotfound”);}
With Java 7:
view plaincopy to clipboardprint?
- Stringcolor=”red”;switch(color){case”red”:System.out.println(“ColorisRed”);break;case”green”:System.out.println(“ColorisGreen”);break;default:System.out.println(“Colornotfound”);}
Conclusion
The switch statement when used with aString
uses theequals()
method to compare the given expression to each value in the case statement and is therefore case-sensitive and will throw aNullPointerException
if the expression is null. It is a small but useful feature which not only helps us write more readable code but the compiler willlikelygenerate more efficient bytecode as compared to theif-then-else
statement.
ShareThis
Related posts:
- Java 7: New Feature – automatically close Files and resources in try-catch-finally2 ways to convert Java Map to String3 ways to serialize Java EnumsHow to trim() No-Break space ( ) when parsing HTMLInstalling Java 7 on Mac OS X
好好扮演自己的角色,做自己该做的事