Thursday 3 November 2016

Using string literals in switch statements

Prior to Java 7, only integer values were the valid arguments in a switch statement.
It is not uncommon to make a decision based on a string value, up till now developers have been using if statements whenever there is a need to make a decision based on String values, use of String in switch statement simplify and result in more readable and efficient code.

Code Snippet to display the use of String in Switch Statement

String day;
            day= "";
            switch(day){
            case "Monday" :
                  System.out.println("1st Day");
                  break;
            case "Tuesday" :
                  System.out.println("2nd Day ");
                  break;
                  default:
                        System.out.println("Holiday ");
            }

When using strings, you need to be careful about the following two issue
  • Null values for strings : Using a string reference variable that is assigned a null value will result in a java.lang.NullPointerException.
  • The case of the string : The evaluation of a case expression is case sensitive in a switch statement.