Java: How To Use Enum in Switch

By Angsuman Chakraborty, Gaea News Network
Tuesday, September 23, 2008

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?

Discussion

Toontje
June 14, 2010: 4:53 am

Some may say useless, but it helped me anyway, thnx!


sanjeev
May 27, 2010: 9:46 am

useless example…

as mentioned in very first post it should be
UserAgent.Type


Thomas
March 14, 2010: 7:14 pm

This is a horribly bad/wrong example of using switch statement with Java enums!

Java beginners, do not do that!


Ummi

albert
October 29, 2009: 8:52 am

This example is obviously wrong. The switch should be an enum variable. For example:

UserAgent variable = UserAgent.FIREFOX;
switch (variable) {
case IE: null; //whatever_must_be_done;
}


wil

Sukka
July 15, 2009: 4:41 pm

Thanks for post

November 24, 2008: 12:20 pm

These are not regular variables but enums to represent user agent for different browsers.

Hope that clarifies…


Martin
November 24, 2008: 7:38 am

Should the switch really be “UserAgent.FIREFOX”?

It would make more sence with something like “UserAgent.Type”, or maybe I am missing something.

Kind Regards
Martin

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :