New Java 7 feature: String in switch support

Source: Internet
Author: User
Document directory
  • Conclusion
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?
  1. String color = "red ";
  2. If (color. Equals ("red ")){
  3. System. Out. println ("color is red ");
  4. } Else if (color. Equals ("green ")){
  5. System. Out. println ("color is green ");
  6. } Else {
  7. System. Out. println ("color not found ");
  8. }

With Java 7:

View plaincopy to clipboardprint?
  1. String color = "red ";
  2. Switch (color ){
  3. Case "red ":
  4. System. Out. println ("color is red ");
  5. Break;
  6. Case "green ":
  7. System. Out. println ("color is green ");
  8. Break;
  9. Default:
  10. System. Out. println ("color not found ");
  11. }
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:

  1. Java 7: new feature-automatically close files and resources in try-catch-finally
  2. 2 ways to convert Java map to string
  3. 3 ways to serialize Java enums
  4. How to trim () No-break space (& #160;) when parsing HTML
  5. 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/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.