Saturday, 23 April 2011

The Evolving switch Statement

One thing about working in programming is that things 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 humble switch statement: at the time of J2SE 1.4 you could make a choice based upon an int value:

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

   
switch (b) {
   
case 1:
      System.out.println
("b is 1");
     
break;
   
case 2:
     
// fall through
   
case 3:
      System.out.println
("b is 2 or 3");
     
break;
   
case 4:
      System.out.println
("b is 4");
     
break;
   
default:
      System.out.println
("b 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;
 
}

This is all fully documented by Oracle. It just goes to show, what will they think of next?

No comments: