Learning JDK 7 Features Part 1 : Strings in switch Statements

Switch statement is enhanced in JDK 7 with the support of String Object. Prior to it JDK 7 release, switch only supports  byte, short, char, and int  litearls. With this release onwards, we use string objects in switch expressions. Its is same as comparing String.equals method for each case. Please note the comparison is CASE- SENSITIVE.  Let see how it works :-

private static String getTypeOfSeasonFromSwitch(String monthArg) {
  
  String typeOfSeason = null;
      switch (monthArg) {
       case "December":    
       case "January":
       case "Febuary":
           typeOfSeason = "Winter";
              break;
          case "March":
          case "April":
          case "May":
           typeOfSeason = "Spring";
              break;
          case "June":
          case "July":
          case "August":
           typeOfSeason = "Summer";
              break;         
          case "September":
          case "October":
          case "November":
           typeOfSeason = "Autumn";
              break;          
          default:
              throw new IllegalArgumentException("Invalid month: " + typeOfSeason);
      }
      return typeOfSeason;
 }

Comments

Popular posts from this blog

Fix double check locking in Java 5

When to use getClass() and instanceOf in Java

Why Time gets truncated with ResutSet getDate() function.