Sunday 10 August 2014

Strings in switch Statements

The switch statement evaluates its expression, then executes all statements that follow the matching case label. Before JDK 7, there is no strings support in switch statement. From JDK 7 onwards, strings supported in switch statement.

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method.

public class StringsInSwitch {
    public static void getDays(String month){
        switch(month){
            case "january":
            case "march":
            case "may":
            case "july":
            case "august":
            case "october":
            case "december":
                    System.out.println("Month has 31 days");
                    break;
            case "april":
            case "june":
            case "september":
            case "november":
                    System.out.println("Month has 30 days");             
            case "february":
                    System.out.println("Month has 28 or 29 days");
        }
    }
    public static void main(String args[]){
        String month = "march";
        getDays(month);
    }
}

Output
Month has 31 days

Since string uses equals method for comparison, so if you pass null it will throw java.lang.NullPointerException.

public class StringsInSwitch {
    public static void getDays(String month){
        switch(month){
            case "january":
            case "march":
            case "may":
            case "july":
            case "august":
            case "october":
            case "december":
                    System.out.println("Month has 31 days");
                    break;
            case "april":
            case "june":
            case "september":
            case "november":
                    System.out.println("Month has 30 days");             
            case "february":
                    System.out.println("Month has 28 or 29 days");
        }
    }
    public static void main(String args[]){
        String month = null;
        getDays(month);
    }
}

Output
Exception in thread "main" java.lang.NullPointerException
 at StringsInSwitch.getDays(StringsInSwitch.java:3)
 at StringsInSwitch.main(StringsInSwitch.java:24)
Java Result: 1




                                                             Home

No comments:

Post a Comment