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");
            /** NullPointerException */
            day = callSwich(null);

      private static String callSwich(String day) {
           String typeOfDay;
           switch (day) {
               case "Monday":
                   typeOfDay = "Start of work week";
               case "Tuesday":
               case "Wednesday":
               case "Thursday":
                   typeOfDay = "Midweek";
               case "Friday":
                   typeOfDay = "End of work week";
               case "Saturday":
               case "Sunday":
                   typeOfDay = "Weekend";
                   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.

Make sure to add a NULL check to avoid NullPointerException.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...