New Java 7 Feature: String in Switch support

    技术2022-05-19  19

    New Java 7 Feature: String in Switch support

    One of the new features added in Java 7 is the capability to switch on a String.

    With Java 6, or less

    view plain copy to clipboard print ? 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 plain copy to clipboard print ? 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 with a String uses the equals() method to compare the given expression to each value in the case statement and is therefore case-sensitive and will throw a NullPointerException if 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 the if-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 this article is from  http://www.vineetmanohar.com/2011/03/new-java-7-feature-string-in-switch-support/


    最新回复(0)