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
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");
}
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:
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/
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)






Comments
Tomasz Nurkiewicz replied on Tue, 2011/03/22 - 2:04am
Piotr Kochanski replied on Tue, 2011/03/22 - 6:35am
String in switch does not sound as a great idea since it promotes hardcoding Strings in the application, which is a very bad practice. I'll be extremly surprised if I ever need to use that feature.
Java needs true enhancements, like sane properties aka getters and setters syntax (yes, it is doable Oracle, see http://projectlombok.org).
Jonathan Fisher replied on Tue, 2011/03/22 - 10:34am
Slava Imeshev replied on Tue, 2011/03/22 - 3:37pm
Regards,
Slava Imeshev
Cacheonix - Reliable Distributed Cache
darryl west replied on Tue, 2011/03/22 - 10:46pm
Jon Nichols replied on Wed, 2011/03/23 - 4:44am
Dirk Hillbrecht replied on Wed, 2011/03/23 - 6:00am
Jessie Mear replied on Wed, 2011/09/07 - 6:46am