User Tools

Site Tools


technology:java:strings_in_case_statements

 

Using Strings in Switch Statements

Its a common thing–in some programming languages–to use Strings in a switch statement.  Unfortunately, Java doesn't support that  as of JDK6 because Strings are objects.  If Java allowed the use of one kind of object in a switch statement, then auguably it would have to allow any kind of object and that would be a considerable language change.  So for now, I can't use Strings in switch statements.

But I've found a way to satisfy my need for using Strings.  It involves using enums and a function to convert a string into the corresponding enum.  Let me explain with an example.  Here is an enum declaration.  It can be public, protected, or private, depending on your needs as a software developer.

private enum Action
    {   Walk, Run, Sit, Drive, Sleep, Eat, novalue;
        public static Action getEnum(String str)
        {
            try {return valueOf(str);}
            catch (Exception ex){return novalue;}
        }
    }

The words on the first line (Walk, Run, etc…) are the enumerated values.  They form the complete set of inputs that my program will accept.   I know this list at design time, so turning them into their own data type provides a degree of type safety that I can use in my switch statement.

The getEnum() method is contained inside the enum list, turning the list into an object (of sorts).  It uses the valueOf() method to convert an incoming string to the corresponding enumerated value.  You can think of it as the brains behind this example.

Next is the switch statement that uses the enum:

private static void doAction(String actionString){
        switch(Action.getEnum(actionString)) {
        case Walk:
            walk();
            break;
        case Run:
            run();
            break;
        case Sit:
            sit();
            break;
        case Drive:
            drive();
            break;
        case Sleep:
            sleep();
            break;
        case Eat:
            eat();
            break;
        default:
            System.out.println("Action '"+actionString+"' does not exist.");
            break;
        }
    }

Notice how clear the syntax is:

  • the switch statement operates using the getEnum() method
  • the compiler enforces that each case value is a member of the enum
  • the case statements are clear and highly readable
  • No quoting or qualifying is necessary
  • the default is matched when no other case statement is matched, thanks to the novalue value

To conclude the example, here is a method body that can make use of the above method:

public static void main(String[] args)
    {
        //accept input from command line
        for (int i = 0; i < args.length ; i++){
            doAction(args[i]);
        }
    }
/home/cfreyer/public_html/data/pages/technology/java/strings_in_case_statements.txt · Last modified: 2009/04/01 10:39 by Chris Freyer