Saturday, 6 January 2018

String in Switch Case in Java

Tags

String literal/constant can be used to control the switch statement in Java, which is not possible in  C/C++. Using a string-based switch is an improvement over using the equivalent sequence of  if/else statements. String literal/constant was included in JDK7.

Important Points:

1. Expensive Operation: Switching string can be more expensive in term of execution rather than switching on primitive data types. Therefore, it is best to switch on strings only in cases in which data is controlled in string form.

2. String should not be NULL:  Remember that expression in any switch statement should not be NULL to avoid NullPointerException from being thrown at run-time.

3. Case Sensitive Comparison: case comparison is case sensitive.

4. Better than If-else: The byte code which java compiler generates from using switch statement that use String object is more efficient than if-else statements.

PROGRAM:

import java.util.Scanner;

public class stringSwitch{

        public static void main(String args[]){

            Scanner in=new Scanner(System.in);

            String str;
            System.out.print("\n\nEnter any of the following: \n\n");
            System.out.print("Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday\n\n\n");



            str=in.next();

            switch(str){

                case "Monday": System.out.println("You have entered Monday");
                               break;
                case "Tuesday": System.out.println("You have entered Tuesday");
                               break;
                case "Wednesday": System.out.println("You have entered Wednesday");
                               break;
                case "Thursday": System.out.println("You have entered Thursday");
                               break;
                case "Friday": System.out.println("You have entered Friday");
                               break;
                case "Saturday": System.out.println("You have entered Saturday");
                               break;
                case "Sunday": System.out.println("You have entered Sunday");
                               break;
                default:       System.out.println("You have selected wrong choice");

            }
        }
}


OUTPUT:



EmoticonEmoticon