Search This Blog

Friday 4 November 2016

String literals in switch statements

Prior to Java 7, only integer values were the valid arguments in a switch statement. It is very common 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 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 issues:
ü  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.

 . . . read more



1 comment: