When using enums in a switch, it is almost natural to assume they will be used like a regular switch. Unfortunately to accomodate enums, Java had to enhance its specification and enums in switch behave differently than regular switch statements in two significant and non-trivial ways.

Sun's Javac says -"enum switch case label must be the unqualified name of an enumeration constant. in its cryptic error message. That's probably French to many. I know I had a tough time understanding this statement.

So let's understand this with a simple example:

switch (UserAgent.FIREFOX) {
    case (UserAgent.IE):
        fail(UserAgent.IE.toString() + " unexpected.");
}

This looks obviously correct doesn't it? Unfortunately it is wrong in two different ways.
Firstly the case should be without the brackets. Secondly only IE should be used but not UserAgent.IE. Let's illustrate both of the above points with a simple (correct) example:

switch (UserAgent.FIREFOX) {
    case IE:
        fail(UserAgent.IE.toString() + " unexpected.");
}

To summarize:

  • In case statement the enum must be used without brackets.
  • In case only the unqualified enum name (like FIREFOX or IE in the above example) must be used.

So now you wouldn't make any more mistakes with Java enums, right?