Nov 2, 2012

Java 7 Overview: String in Switch Support

jdk 7Prior to Java 7, Switch statements work either with primitive types or enumerated data types. Java 7 introduced ability to Switch on String type.
The issue worth mentioning about switch statement when used with a String type is, it uses equals() method to compare the expression pass to it, with each value in the case statement, which made it case-sensitive and will throw a NullPointerException if the expression is null.
As a result, checking for null parameter and converting the string to lower
case is necessary to prevent NullPointerException.
Nonetheless  the feature is useful and helps in writing more readable and compiler optimized code, compared to the old if statement that we have being using.

Traditionally, this is how we used to deal with string prior to Java 7 update for the Switch in String  support.  To compare the Strings value is kind a  repetitive task and not that clearer.

This Java example determines Days in every Month of the year.
public class WithNoStringInSwitch{
     int getDaysMonth (String month, int year){
         if(month.equals("April") || month.equals("June") || 
                 month.equals("September") || month.equals("November")){
             return 30;
         else if(month.equals("January") || month.equals("March") ||
                 month.equals("May") || month.equals("July") || 
                 month.equals("August") || month.equals("December")){
             return 31;
         else if(month.equals("February")){
             return ((year % 4 == 0 && year %100 != 0) || year %400 == 0)? 29:28;
             throw new IllegalArgumentException();

The following code is the same example as the one above, but featuring the new Switch in String methodology. As you may see its more cleaner and have less complicated code compared to the above example. As I said, we checked if the expression in the switch statement is not null to prevent a NullPointerException from being thrown.
public  class StringInSwitch {
    public int getDaysMonth(String month, int year){
        if(month == null || year <= 0){
            System.out.println("Invalid parrameter! try again");
            return 0;
            case "April":
            case "June":
            case "September":
            case "November":
                return 30;
            case "January":
            case "March":
            case "May":
            case "July":
            case "August":
            case "October":
            case "December":
                return 31;
            case "February":
                return ((year %4 == 0 && year% 100 != 0) || year% 400 == 0)? 29:28;
                throw new IllegalArgumentException();
Related Posts

Java 7 Overview: Automatic Resource Management  

Java 7 Overview: Multi-Catch Support

No comments:

Post a Comment