Use of String variable in Java Switch Statement

There is no way to perform a true switch on a String in Java. With the arrival of JDK 5.0 and its implementation of enum, a reasonably close approximation of this can be done using the following code.

Create an enum :

 public enum Months{ JAN, FEB, MAR, APRIL;}

 

Given this enum, the following switch statement could be used:

switch (Months.valueOf(str))
{
case JAN:
case FEB:
// processing
break;
default:
// processing ...
}

Enum.valueOf() matches the given String to the actual enum name using the same basic hashcode() matching technique that earlier proposals have suggested; but with this , all of that machinery is generated by the compiler and Enum implementation. The set of possible String values is also maintained in a more structured way when held in an enum.

Of course, the above suffers from the serious drawback that Enum.valueof() can throw an unchecked IllegalArgumentException or NullPointerException. The only real way to get around this issue is to create a new static method that absorbs these Exceptions and instead returns some default value:

 

public enum Months {
 JAN, FEB, MAR, APR, JUN, JUL, AUG, SEP, OCT, NOV,DEC,NOVALUE;
public static Months toDay(String str)
{
   try { return valueOf(str); } catch (Exception ex) { return NOVALUE; }
}
 }

Then the switch can be written to include a default clause that handles unexpected String values:

switch (Months.toDay(str)) {
 case JAN:
case FEB:
case MAR:
// etc ...
default:
// any non-Day value
}


 

Leave a Reply

Your email address will not be published. Required fields are marked *