Tuesday, August 16, 2011

JDK 7: Strings in switch Statement

Another useful functionality added in JDK7 is the ability to use Strings in switch statements. The Strings are compared using their equals method (hashcode) and as such are case-sensitive.

public String getSeasonFromMonth(String month) {
    String season;

    switch (month) {
        case "December":
        case "January":
        case "February":
            season = "Winter";
            break;

        case "March":
        case "April":
        case "May":
            season = "Spring";
            break;

        case "June":
        case "July":
        case "August":
            season = "Summer";
            break;

        case "September":
        case "October":
        case "November":
            season = "Fall";
            break;

        default:
            throw new IllegalArgumentException("Invalid Month - " + month);
    }

    return season;
}


The compiler also generates more efficient byte-code from the switch statement instead of chained if-then-else statements.

No comments:

Post a Comment