• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Enum constants in Switch

 
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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,
 
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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 don't even know how to spell CIA. But this tiny ad does:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic