Sorcerer's Tower

Switch on String in Java

For anyone working with any other modern language, (such as CFML, C#, JavaScript, Ruby, and more), using a String within a switch-case statement is not an issue, and probably something you've done many times without thinking about.

However, when working in Java you cannot use strings in a switch statement.

The insanity of this alone is amazing, but searching for a solution and trawling through all the suggestions of "just use if elseif else" and similar idiotic ideas has been really depressing.

Even once I found hints of the solution, getting discussions from C# polluting my results caused the frustration of having to dig around even further to find the actual correct implementation.


So, in the hope of avoiding such agony and gloom for anyone else who finds themselves in a similar situation, here is the solution I eventually uncovered:

private enum Command
{ help , add , info , rel , note , reset , novalue ;
	public static Command fromString(String Str)
	{
		try {return valueOf(Str);}
		catch (Exception ex){return novalue;}
	}
};

private static void takeAction( String Action )
{
	switch ( Command.fromString(Action) )
	{

		case help:
			showHelp();
		break;

		case add:
			addTask();
			showTask();
		break;

		// ...

		default:
			showError( "invalid command" );
			displayUsage();
		break;

	}

}

In explanation of the example code above...

First is the declaration of an enum - an "enumerated type", a set of named constants.

The contents of the braces contain the comma-delimited set of accepted values - a "Command" can be any of those six, but nothing else.

private enum Command { help , add , info , rel , note , reset , novalue }

The enum declaration cannot be local to the relevant function, it must go outside.

Update: In order to allow a default case (without throwing an exception), the enum needs to contain a function with a try/catch block added. This function is separated from the values within the enum with a semi-colon.

public static Command fromString(String Str)
{
	try {return valueOf(Str);}
	catch (Exception ex){return novalue;}
}

After the enum is setup, we have a standard function declaration with a String "Action" argument that we want to switch on.

Within the switch statement, we need to convert Action to an enum value.

To do this, what we have is switch( [enum].fromString([string]) )

The rest should be obvious - note that double quotes are neither required nor allowed with enums, so we have case [command] rather than case "[command]"

Any new cases need to be added both to the switch and to the enum declaration.


Note: This solution works for Java 5.0 and newer.
(Java 5 is also known as Java 1.5.0, but Sun wanted bigger version numbers and dropped the 1s.)