String In Switch-Java 7 New Concept

Introduction

 
In this article we will discuss String in a switch statement; a new feature of Java 7. So for explaining this topic we take a short look at switch, string and some switch cases.
 

Strings In Java

 
A string is widely used in Java, they are a sequence of characters (sometimes called a character array). In Java, strings are objects.
 
Java provides the String class to create and manipulate strings.
 

How to Create a String?

 
The general way to create a string is:
  1. String welcome=" welcome to Java world";   
Let's see an example to display the simple string "Welcome". 
  1. public class StringEx  
  2.   {  
  3.     public static void main(String args[])  
  4.       {  
  5.         char[] WelcomeArray = { 'W''e''l''c''o''m''e'};  
  6.         String WelcomeString = new String(WelcomeArray);   
  7.         System.out.println( WelcomeString );  
  8.       }     
  9.   }   
Output
 
fig1.jpg
 

Switch case in Java

 
Switch statements reduce the workload, since without a switch we use if and else many times instead of the switch. Let's see a sample of if and else without a switch:
  1. if (x == 0) doSomework0();  
  2. else if (x == 1) doSomework1();  
  3. else if (x == 2) doSomework2();  
  4. else if (x == 3) doSomework3();  
  5. else if (x == 4) doSomework4();  
  6. else doSomeworkElse();  
Java has a shorthand for these types of multiple if statements, the switch-case statement. Here's how you'd write the above using a switch-case:
  1. switch (x)  
  2.   {  
  3.     case 0:   
  4.     doSomework0();  
  5.     break;  
  6.     case 1:   
  7.     doSomework1();  
  8.     break;  
  9.     case 2:   
  10.     doSomework2();  
  11.     break;  
  12.     case 3:   
  13.     doSomework3();  
  14.     break;  
  15.     case 4:   
  16.     doSomework4();  
  17.     break;  
  18.     default:   
  19.     doSomeworkElse();  
  20.  }  
In this example x must be a variable. x is compared to each case value. In case 0 the x must be compared with x==0 if it is then subsequent code will execute, similarly x will work according to other cases. If no cases are matched then the default action is triggered.

Purpose of switch

 
The if statement only evaluates a boolean value (only two possible values True and False). The switch statement will execute on many expressions based on an integer (including char) or enum value.
 
Switch keywords
 
1. switch
The Switch statement is followed by an expression in parentheses, that is followed by the cases, all enclosed in braces. The Switch statement works using cases dependent on the value of expressions.
 
2. Case 
The case contains a colon and an integer constant.
 
3. default 
If no case value matches the switch expression value then execution falls to the default clause. This is the equivalent of the last "else" for a series of if statements.
 
4. break 
The break statement causes execution to exit to the statement after the end of the switch. If there is no break then execution flows thru into the next case. Flowing directly into the next case is nearly always an error.
 
Example
 
Let's see an example of how switch cases work!
  1. import java.io.*;  
  2. public class SwitchEx  
  3.   {  
  4.     public static void main(String args[]) throws Exception  
  5.       {  
  6.         int choice;  
  7.         // we make a month chart to test switch cases  
  8.         System.out.println("Enter 1 for January.");  
  9.         System.out.println("Enter 2 for Febrary");  
  10.         System.out.println("Enter 3 for March.");  
  11.         System.out.println("Enter 4 for April.");  
  12.         System.out.println("Enter 5 for May.");  
  13.         System.out.println("Enter 6 for June.");  
  14.         System.out.println("Enter 7 for July.");  
  15.         System.out.println("Enter 8 for August.");  
  16.         System.out.println("Enter 9 for September.");  
  17.         System.out.println("Enter 10 for October.");  
  18.         System.out.println("Enter 11 for November.");  
  19.         System.out.println("Enter 12 for December.");  
  20.         System.out.print("\n Whats your choice : ");  
  21.         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));  
  22.         try  
  23.           {  
  24.             choice=Integer.parseInt(in.readLine());  
  25.             switch(choice)  
  26.               {   
  27.                 case 1: System.out.println("January");  
  28.                 break;  
  29.                 case 2: System.out.println("Febrary");  
  30.                 break;  
  31.                 case 3: System.out.println("March");  
  32.                 break;  
  33.                 case 4: System.out.println("April");  
  34.                 break;  
  35.                 case 5: System.out.println("May");  
  36.                 break;  
  37.                 case 6: System.out.println("June");  
  38.                 break;  
  39.                 case 7: System.out.println("July");  
  40.                 break;  
  41.                 case 8: System.out.println("August");  
  42.                 break;  
  43.                 case 9: System.out.println("September");  
  44.                 break;  
  45.                 case 10: System.out.println("October");  
  46.                 break;  
  47.                 case 11: System.out.println("November");  
  48.                 break;  
  49.                 case 12: System.out.println("December");  
  50.                 break;  
  51.                 default: System.out.println("Wrong entry!");  
  52.                 break;  
  53.                 }  
  54.            }  
  55.         catch(NumberFormatException ey)  
  56.           {  
  57.             System.out.println(ey.getMessage() + " enter only numeric value.");  
  58.             System.exit(0);  
  59.           }  
  60.       }  
  61.   }  
Output
 
fig-2.jpg
 
String in switch: Java 7 new feature
 
Switch statements work either with primitive types (e.g byte, short, long, int, etc) or enumerated types. Java 7 introduced another type that we can use in Switch statements:
 
the String type.
 
The method of working on strings is crude. Java 7 improves the program by enhancing the Switch statement, that takes a String type as an argument.
Let's see a previous example using a String in a switch this time. In this example, a string is invoked in the switch statement which can't be dne in prior versions of Java. So it might be helpful for reducing if-else statements.
  1. public class StringSwitchEx  
  2.   {  
  3.     public static int getMonthNumber(String month)  
  4.       {  
  5.         int monthNumber = 0;  
  6.         if (month == null)  
  7.           {  
  8.             return monthNumber;  
  9.           }  
  10.         switch (month.toLowerCase())  
  11.           {  
  12.             case "january":  
  13.             monthNumber = 1;  
  14.             break;  
  15.             case "february":  
  16.             monthNumber = 2;  
  17.             break;  
  18.             case "march":  
  19.             monthNumber = 3;  
  20.             break;  
  21.             case "april":  
  22.             monthNumber = 4;  
  23.             break;  
  24.             case "may":  
  25.             monthNumber = 5;  
  26.             break;  
  27.             case "june":  
  28.             monthNumber = 6;  
  29.             break;  
  30.             case "july":  
  31.             monthNumber = 7;  
  32.             break;  
  33.             case "august":  
  34.             monthNumber = 8;  
  35.             break;  
  36.             case "september":  
  37.             monthNumber = 9;  
  38.             break;  
  39.             case "october":  
  40.             monthNumber = 10;  
  41.             break;  
  42.             case "november":  
  43.             monthNumber = 11;  
  44.             break;  
  45.             case "december":  
  46.             monthNumber = 12;  
  47.             break;  
  48.             default:   
  49.             monthNumber = 0;  
  50.             break;  
  51.           }  
  52.         return monthNumber;  
  53.       }  
  54.     public static void main(String[] args)  
  55.       {  
  56.         String month = "June";  
  57.         int returnedMonthNumber =StringSwitchEx.getMonthNumber(month);  
  58.         if (returnedMonthNumber == 0)  
  59.           {  
  60.             System.out.println("Invalid month");  
  61.           }  
  62.         else  
  63.           {  
  64.             System.out.print("The selected month no is : ");  
  65.             System.out.print(returnedMonthNumber);  
  66.           }  
  67.       }  
  68.   }  
Output
 
fig-3.jpg


Similar Articles