Monday, 5 August 2013

Java - Switch over String

As the answer of erickson to this post of StackOverflow, "Switch statements with String cases has been implemented in Java SE 7, at least 16 years after they were first requested."

For anyone who is using an JDK before 7, here is an example code of how to use it.

1. Create an enum of the possible strings
Here is an example:

public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY, NOVALUE;

public static Day toDay(String str) {
try {
return valueOf(str);
} catch (Exception ex) {
return NOVALUE;
}
}
}

As this post stated, the normal enum code suffers from serious drawback taht Enum.valueOf() can throw an unchecked illegalArgumentException of NullPointerException. The best way to get around this is to create a new static method that absorbs these Exceptions and instead return some default value.

2. Create an switch which use the method toUpperCase() to do the matches
Because all the enum has been declared upper case and switch is case sensitive, it is mandatory to use the method toUpperCase() of String to do correctly the Switch.

Here is an example:

public static void main(String[] args) {
String today = "wednesday";
switch (Day.toDay(today.toUpperCase())) {
case MONDAY:
System.out.println("Monday");
break;
case TUESDAY:
System.out.println("Tuesday");
break;
case WEDNESDAY:
System.out.println("Wednesday");
break;
case THURSDAY:
System.out.println("Thursday");
break;
case FRIDAY:
System.out.println("Friday");
break;
case SATURDAY:
System.out.println("Saturday");
break;
case SUNDAY:
System.out.println("Sunday");
break;
default:
System.out.println("Not an earch day " + today);
break;
}
}

Source:

SourceCode:
Here is an example of the code: https://github.com/jiahaoliuliu/SwitchString

No comments:

Post a Comment