This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Svelte and Sapper in Action and have Mark Volkmann on-line!
See this thread for details.
Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Understanding enum

 
Ranch Hand
Posts: 34
1
MyEclipse IDE Tomcat Server Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

can anybody tell me how enum is advantageous if i am using inside class instead of static variable keeping out of this.....
 
Saloon Keeper
Posts: 12269
259
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please rephrase your question? I'm not sure what you meant.
 
Ranch Hand
Posts: 58
Eclipse IDE C++ Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you strictly want a variable to assume a value within a specific set of constants, you should be better off with an enum.


In the above example, 'Color c' can take only four values(e.g. Color.RED, Color.YELLOW, Color.BLUE or Color.GREEN), whereas, in case of 'int color', nothing stops me from assigning any value outside the four static final int constants.
 
Stephan van Hulst
Saloon Keeper
Posts: 12269
259
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You've already identified the most important advantage yourself.

It doesn't make sense for a Color to be 1 or 2 or 5. Colors should be RED or GREEN, etc. and there should be nothing else - like an integer value - that is of importance.

Enums provide this important distinction.
 
Whoever got anywhere by being normal? Just ask this exceptional tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic