Monday 4 May 2015

Enhancement of switch Statement in Java 1.4,Java 5 and Java 7

One thing about working in programming is that things will change; you can count on it, new things are written, tools become in vogue and techniques go in and out of fashion.

One thing that changes somewhat less often is the Java language itself, though it is evolving and for the better.

Consider the switch statement: at the time of J2SE 1.4 you could make a choice based upon an int value:

 // switchParameter is automatically converted to an int
    byte switchParameter = 6;

    switch (switchParameter ) {
    case 1:
      System.out.println("switchParameter  is 1");
      break;
    case 2:
      // fall through
    case 3:
      System.out.println("switchParameter  is 2 or 3");
      break;
    case 4:
      System.out.println("switchParameter  is 4");
      break;
    default:
      System.out.println("switchParameter  is invalid");
      break;
    }

...and because of the compiler’s inherent casting inbuilt casting this meant that you could switch using a byte, short, char or int. It could not be anything else: boolean, double or object reference etc.

Then along came Java 5 and the switch statement evolved to include enums.

private enum Colour {
    RED, GREEN, BLUE, YELLOW;
  }
 
  private static void switchEnumTest() {
   
    Colour val = Colour.GREEN;
   
    switch(val) {
    case RED:
      System.out.println("Your lucky colour is red");
      break;
    case GREEN:
      System.out.println("Your lucky colour is green");
      break;
    case BLUE:
      System.out.println("Your lucky colour is blue");
    case YELLOW:
      System.out.println("Or is it yellow?");
      break;
    // No default as we have all the bases covered. 
    }
  }
And, what do you know? switch is changing again. In Java SE 7 a switch statement can accept a String as an inpout argument:

public static int getMonthNumber(String month) {

    int monthNumber = 0;

    if (month == null) {
      return monthNumber;
    }

    switch (month.toLowerCase()) {
    case "january":
      monthNumber = 1;
      break;
    case "february":
      monthNumber = 2;
      break;
    case "march":
      monthNumber = 3;
      break;
    case "april":
      monthNumber = 4;
      break;
    case "may":
      monthNumber = 5;
      break;
    case "june":
      monthNumber = 6;
      break;
    case "july":
      monthNumber = 7;
      break;
    case "august":
      monthNumber = 8;
      break;
    case "september":
      monthNumber = 9;
      break;
    case "october":
      monthNumber = 10;
      break;
    case "november":
      monthNumber = 11;
      break;
    case "december":
      monthNumber = 12;
      break;
    default:
      monthNumber = 0;
      break;
    }

    return monthNumber;
  } 
 
 

If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

No comments:

Post a Comment