
public class prasTest {
public enum test {
first, second, third, novalue;
public static test toValidStr(String str) {
try {
return valueOf(str);
}
catch (Exception e) {
return novalue;
} }
}
public static void main(String args[]) {
String str = “second”;
switch (test.toValidStr(str)) {
case first:
System.out.println(“first”);
break;
case second:
System.out.println(“second”);
break;
case third:
System.out.println(“third”);
break;
default: System.out.println(“default”);
break;
} } }
Here, in the above implementation we could have directly used enum.valueOf() in switch statement instead of toValidStr() but, just to handle the IllegalArgument Exception which is thrown when some non-enum string is given as the input to switch, a new static method (toValidStr() ) is created and used. Enum.valueOf() method matches the given string to the actual enum string using the hashcode matching mechanism . The maintenance of possible string values is also eased and more structured with the use of enums.
If you would like to make a comment, please fill out the form below.