Friday, October 29, 2010

Strings in Switch statements - a new JDK 7 feature

JDK 7 is the next release of Java language. There are lot of expectations from this release. For the first time Java is being modeled outside Sun Microsystems. Now JDK 7 has got a net host, openJdk community.

There are quite a few features planned in JDK 7. Some of them may prove to be a milestone for Java language. But my personal liking is a very small feature rather project called Project Coin. Coin serves to add small language features to Java which will make programmer's life easy. The JavaOne 2010 presentation for Project Coin lists the following features as accepted ones in JDK 7 time frame.

  • Binary literals and underscores in literals
  • Strings in switch
  • Varargs warnings
  • Diamond
  • Multi-catch and more precise rethrow
  • try-with-resources (formerly known as Automatic Resource Management, ARM)

Out of these features, the most attractive to me was "Strings in switch". This is something I've longed for from my college days. I mean, though it was not Java (it was C) still I dreamed of writing switch statements with strings. Finding a unique hashcode for each string to be switched was tedious. In Java 5, usage of Enum constants in a switch statement was allowed. Still it did not fit.
Why do you use a switch block? Simple, when we have many alternative possibilities. See the below code -

int monthNameToDays(String s, int year) 
   if(s.equals("April") || s.equals("June") ||
      s.equals("September") || s.equals("November"))
      return 30;
   if(s.equals("January") || s.equals("March") ||
      s.equals("May") || s.equals("July") ||
      s.equals("August") || s.equals("December"))
      return 31;
      return 28;
      // do nothing

This method returns no. of days when you pass the name of the month. But till now Java programmers used to  write the method in this way. Some really cool dudes will try to construct an enum and use it in a switch block. But still we need a string comparison in order to set the value to the switch variable. Not too cool.

Won't it be great if we can do the same code using switch construct. JDK 7 is coming with exactly the same promise. It will allow developers to use strings in switch. Check it out-

int monthNameToDays(String s, int year) 
      case "April":
      case "June":
      case "September":
      case "November":
           return 30;
      case "January":
      case "March":
      case "May":
      case "July":
      case "August":
      case "December":
           return 31;
      case "February":

This feature requies change in JLS as well as in Java compiler and JRE. The implementation still uses string.hashCode() to find out the integer which can be used in native switch blocks. But now this will be done by java compiler. This will reduce the effort of Java developer and make the code more readable. The detailed strings in switch proposal can be found here.

No comments:

Post a Comment