aspose file tools*
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
Author

Enum constants in Switch

Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774
Hi,

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.

Thanks,


Prithvi,
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.

SCJP 6
Mykola Kurutin
Greenhorn

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.
 
 
subject: Enum constants in Switch