tags:

views:

865

answers:

5

What results when you pass an empty string to a Java enum .valueOf call?

For example:

public enum Status
{
   STARTED,
   PROGRESS,
   MESSAGE,
   DONE;
}

and then

String empty = "";

switch(Status.valueOf(empty))
{
   case STARTED:
   case PROGRESS:
   case MESSAGE:
   case DONE:
   {
      System.out.println("is valid status");
      break;
   }
   default:
   {
      System.out.println("is not valid");
   }
}

Basically, I want to know if I'm using a switch statement with the enum, will the default case be called or will I get an exception of some sort?

+2  A: 

I just tried your code. It throws an IllegalArgumentException. Just like the documentation says.

Etienne de Martel
Funnily, I didn't realize that there was javadoc for that method. http://java.sun.com/javase/6/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,%20java.lang.String)
Jay R.
@Jay: No, that is a different method (note how it takes two arguments). The method you called is specified directly in the Java Language Specification, which also mentions the IllegalArgumentException: http://java.sun.com/docs/books/jls/third_edition/html/classes.html#302265
newacct
+4  A: 

You should get an IllegalArgumentException if the name is not that of an enum (which it wont be for the empty string). This is generated in the API docs for all enum valueOf methods. You should get a NullPointerException for null. It's probably not a good idea to give a dummy value to your String variable (nor to allow the last case/default to fall through).

Tom Hawtin - tackline
+1  A: 

Status.valueOf behaves the same as Enum.valueOf

Peter Lawrey
+1  A: 

Why dont you just run the code or read the javadocs ?

Executing code is the ultimate source of truth. If the code does the wrong thing it does the wrong thing and needs to be fixed.

mP
I thought it might be a useful question that could be searched on SO. The documentation for that particular method isn't in the java api docs, although it is in the lang spec.
Jay R.
+1  A: 

method: valueOf

Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

Parameters:
    enumType - the Class object of the enum type from which to return a constant
    name - the name of the constant to return 
Returns:
    the enum constant of the specified enum type with the specified name 
Throws:
    IllegalArgumentException - if the specified enum type has no constant with the specified name, or **the specified class object does not represent an enum type** 
    NullPointerException - if **enumType or name is null**

so it will flag these exceptions,

sazamsk