ProAnswers.org

How to pass string to switch statement in Java

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

switch (Day.valueOf(str))
{
case SATURDAY:
case SUNDAY:
// weekend processing …
break;
default:
// weekday processing …
}

Do some error handling like

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

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

}

switch (Day.toDay(str))
{
case SUNDAY:
case MONDAY:
case TUESDAY:
// etc …
default:
// any non-Day value
}

Hope it help