New Java 7 Feature: String in Switch support

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 aStringuses theequals()method to compare the given expression to each value in the case statement and is therefore case-sensitive and will throw aNullPointerExceptionif 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-elsestatement.

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

好好扮演自己的角色,做自己该做的事

New Java 7 Feature: String in Switch support

相关文章:

你感兴趣的文章:

标签云: