June 19, 2016

Switch Case With Strings | Java

01:51 Posted by Durga swaroop Perla , , , No comments
Switch Case is certainly one of the most widely used programming constructs. It is just as widely used in Java as in any other language.java-logo
Up until Java 7, switch in Java did not support String type in the case statement. So, if you want to perform multiple comparisons on Strings, the only way you were able to do it was by using multiple If - Else Statements which is certainly not pretty!
But, then in Java 7 they have introduced Switch With Strings and it was welcomed by everyone who had to write those terrible if-else ladders. So, Let’s see how we can use Strings in a Case statement.

public class StringCase{
 public static void main(String [] args)    {
  String weekDay=null;
  System.out.println("Monday is day" +getDayNum("Monday")+  "of the week");
  System.out.println("Sunday is day" +getDayNum("Sunday")+ "of the week");
 }
 public static int getDayNum(String weekDay){
  int dayNum=0;
  switch(weekDay){
   case "Monday":
    dayNum = 1; break;
   case "Tuesday":
    dayNum = 2; break;
   case "Wednesday":
    dayNum = 3; break;
   case "Thursday":
    dayNum = 4; break;
   case "Friday":
    dayNum = 5; break;
   case "Saturday":
    dayNum = 6; break;
   case "Sunday":
    dayNum = 7; break;
   default:
    dayNum = -1; break;
  }
  return dayNum;
 }
}

And, as you can guess the Output is as follows.

Monday is day 1 of the week
Sunday is day 7 of the week

Image Credits:
Java logo image used from http://www.rotati.com/images/java-logo.png

0 comments:

Post a Comment

Please Enter your comment here......