Java 7 - Switch case with non-primitive (String)

 

In last tutorial we have discussed about multi-catch feature in Java 7. Now lets see how Java 7 supports non-primitive datatype in switch case. Until Java 6 we had only switch cases support for primitive datatypes like int, char, short, and byte.  

      Below small example will gives you how switch case works until Java 6 with primitive datatype int.



public class MySwitch {
 public static void main(String[] args) {
  int days = Integer.parseInt(args[0]);
  switch(days){
   case 0: 
    System.out.println("Monday");
    break;
   case 1: 
    System.out.println("Tuesday");
    break;
   case 2: 
    System.out.println("Wednesday");
    break;
   case 3: 
    System.out.println("Thursday");
    break;
   case 4: 
    System.out.println("Friday");
    break;
   case 5: 
    System.out.println("Saturday");
    break;
   case 6: 
    System.out.println("Sunday");
    break;
   default: 
    System.out.println("Sorry Invalid Input!!!");    
  }
 }
}


      In above program we have taken the command line input value and checked for day of week by using switch case. Here we have used primitive datatype int for variable "days".

      Additionally in Java 7 we have got non-primitive datatype String also can be used in the Switch case. Below example will give the same code of Java 7 Switch case with String.



public class MySwitch {
 public static void main(String[] args) {
  String day = args[0];
  
  switch(day.toLowerCase()){
   case "monday": 
    System.out.println("Hai its weeks 1st day...");
    break;
   case "tuesday": 
    System.out.println("Hai its weeks 2nd day...");
    break;
   case "wednesday": 
    System.out.println("Hai its weeks 3rd day...");
    break;
   case "thursday": 
    System.out.println("Hai its weeks 4th day...");
    break;
   case "friday": 
    System.out.println("Hai its weeks 5th day...");
    break;
   case "saturday": 
    System.out.println("Hai its weeks 6th day...");
    break;
   case "sunday": 
    System.out.println("Hai its weeks 7th day...");
    break;
   default: 
    System.out.println("Sorry Invalid Input!!!");    
  }
 }
}



Hope you are clear on new switch case in Java 7 and lets see other Java 7 feature in next tutorial. 






    

No comments:
Write comments