Saturday, July 30, 2011

Java 7: Strings in Switch

Strings in switch gives you the ability to switch on string values just like you can currently do on primitives. Previously, you would have had to create chained if-else tests for string equality or introduce an enum, which is not necessary anymore.

The strings-in-switch feature works by first switching on the hashCode of the String and then performing an equals test.

Here is an example of a method which returns the number of days in a month. It uses if-else statements and string equality:
public static int getDaysInMonth(String month, int year) {
    if("January".equals(month) ||
       "March".equals(month)   ||
       "May".equals(month)     ||
       "July".equals(month)    ||
       "August".equals(month)  ||
       "October".equals(month) ||
       "December".equals(month))
        return 31;
    else if("April".equals(month)    ||
            "June".equals(month)     ||
            "September".equals(month)||
            "November".equals(month))
        return 30;
    else if("February".equals(month))
        return ((year % 4 == 0 && year % 100 != 0) ||
                 year % 400 == 0) ? 29 : 28;
    else
        throw new IllegalArgumentException("Invalid month: " + month);
}
The same code can be rewritten neatly using strings-in-switch as follows:
public static int getDaysInMonth2(String month, int year) {
    switch(month) {
        case "January":
        case "March":
        case "May":
        case "July":
        case "August":
        case "October":
        case "December":
            return 31;
        case "April":
        case "June":
        case "September":
        case "November":
            return 30;
        case "February":
            return ((year % 4 == 0 && year % 100 != 0) ||
                     year % 400 == 0) ? 29 : 28;
        default:
            throw new IllegalArgumentException("Invalid month: " + month);
    }
}
Further Reading:
Strings in switch Statements

No comments:

Post a Comment