Java: How To Use Enum in Switch
By Angsuman Chakraborty, Gaea News NetworkTuesday, 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?
Tags: Enum type safety, Java Enum, Java Programming, Java Tips
sanjeev |
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; |
wil |
Sukka |
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 |
Toontje