String in switch case in java 7

Prior to Java 7 the Switch-Case statement did not have support for String data types. This anomaly has been corrected with Java adding support for String in Switch Case in Java 7. This article shows how strings can be used in switch case.

As per Java documentation the byte code of Switch-Case statement holdsĀ a slight edge in performance over the traditional if-then-else statement in handling the same logic. Lets look at an example of using String data type for Switch-Case…

package com.javabrahman.corejava;
 public class StringsInSwitchStatement {
  public static void main(String args[]) {
   //TEST statements for String usage in Switch statement
   System.out.println("Monday is day number->" + getNumberOfDay("Monday"));
   System.out.println("Monday is day number->" + getNumberOfDay("Friday"));
  }
  private static int getNumberOfDay(String day) {
  int numberOfDay = -1;
  switch (day) {//day is of type String
   case "Monday": numberOfDay = 1; break;
   case "Tuesday": numberOfDay = 2; break;
   case "Wednesday": numberOfDay = 3; break;
   case "Thursday": numberOfDay = 4; break;
   case "Friday": numberOfDay = 5; break;
   case "Saturday": numberOfDay = 6; break;
   case "Sunday": numberOfDay = 7; break;
   default: numberOfDay = -1; break;
  }
  return numberOfDay;
 }
}