Wednesday 29 June 2016

Strings in switch Statements

 Since: Jdk 1.7
public class SwitchStringExample {

      public static void main(String[] args) {
           
            String day = callSwich("Monday");
            System.out.println(day);
     
            /** NullPointerException */
            day = callSwich(null);
            System.out.println(day);
      }


      private static String callSwich(String day) {
           String typeOfDay;
           switch (day) {
               case "Monday":
                   typeOfDay = "Start of work week";
                   break;
               case "Tuesday":
               case "Wednesday":
               case "Thursday":
                   typeOfDay = "Midweek";
                   break;
               case "Friday":
                   typeOfDay = "End of work week";
                   break;
               case "Saturday":
               case "Sunday":
                   typeOfDay = "Weekend";
                   break;
               default:
                   throw new IllegalArgumentException("Invalid day" + day);
           }
           return typeOfDay;
      }
}

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; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

Note:
Make sure to add a NULL check to avoid NullPointerException.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...