Over a million developers have joined DZone.

New Java 7 Feature: String in Switch support

· Java Zone

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.

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");
}

With Java 7:

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.

 

From http://www.vineetmanohar.com/2011/03/new-java-7-feature-string-in-switch-support/

The Java Zone is brought to you in partnership with JetBrains.  Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience.

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}