Friday, May 18, 2012

String in Switch Statement!!!

 In java, if we can use the string in the switch statement, it would be more helpful for java developer. Here is the solution from JDK 7.Hereafter we can use switch statement in JDK7 and later.
Example:

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + 
         dayOfWeekArg);
     }
     return typeOfDay;
}