File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Enum constants in Switch Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Enum constants in Switch" Watch "Enum constants in Switch" New topic

Enum constants in Switch

Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774

I have a very stupid doubt in using enums in switch. I am really confused though.
This is a sample of code from K&B chapter 5

The output in this case is green. I read somewhere specification says that, if you have to use enum's as case
constant, you must specify them without fully qualified name. I am puzzled how compiler is interpreting red and
green and blue in this case as a case label.

Hope someone can clarify this confusion.


My Blog, Follow me on Twitter,Scjp Tips, When you score low in mocks, Generics,Scjp Notes, JavaStudyGroup
Larry Chung
Ranch Hand

Joined: Feb 02, 2010
Posts: 247
From one perspective, the "red and green and blue" are interpreted by the compiler as legal enum constants because the variable c is of enum type Color. If you create another enum such as Direction and try it like so:

then the compiler will report that red and green and blue "cannot be resolved or is not a field" because the switch is now on Direction, not Color.

Mykola Kurutin

Joined: Mar 15, 2010
Posts: 1
Prithvi Sehgal wrote:

The output in this case is green.

Here is the actual output:
I am green
I am blue
Blah blah

Don`t forget about break; at the end of each case.
I agree. Here's the link:
subject: Enum constants in Switch
It's not a secret anymore!