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

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.

Related posts:

  1. Java 7: New Feature – automatically close Files and resources in try-catch-finally
  2. 3 ways to serialize Java Enums
  3. 2 ways to convert Java Map to String
  4. Installing Java 7 on Mac OS X
  5. Amazon adds SimpleDB Support in AWS Toolkit for Eclipse

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get Adobe Flash playerPlugin by wpburn.com wordpress themes