New Java 7 Feature: String in Switch support
Join the DZone community and get the full member experience.
Join For FreeOne of the new features added in Java 7 is the capability to switch on a String.
With Java 6, or less
With Java 7:
String color = "red";Conclusion
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");
}
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.
From http://www.vineetmanohar.com/2011/03/new-java-7-feature-string-in-switch-support/
Opinions expressed by DZone contributors are their own.
Comments