4/13/2008

Java enum examples

Simple enum. The ; after the last element is optional, when this is the end of enum definition.
public enum Color {
 WHITE, BLACK, RED, YELLOW, BLUE;  //; is optional
}
Enum embedded inside a class. Outside the enclosing class, elements are referenced as Outter.Color.RED, Outter.Color.BLUE, etc.
public class Outter {
 public enum Color {
   WHITE, BLACK, RED, YELLOW, BLUE
 }
}
Enum that overrides toString method. A semicolon after the last element is required to be able to compile it. More details on overriding enum toString method can be found here.
public enum Color {
 WHITE, BLACK, RED, YELLOW, BLUE;  //; is required here.

 @Override public String toString() {
   //only capitalize the first letter
   String s = super.toString();
   return s.substring(0, 1) + s.substring(1).toLowerCase();
 }
}
Enum with additional fields and custom constructor. Enum constructors must be either private or package default, and protected or public access modifier is not allowed. When custom constructor is declared, all elements declaration must match that constructor.
public enum Color {
 WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

 private int code;

 private Color(int c) {
   code = c;
 }

 public int getCode() {
   return code;
 }
Enum that implements interfaces. Enum can implement any interfaces. All enum types implicitly implements java.io.Serializable, and java.lang.Comparable.
public enum Color implements Runnable {
 WHITE, BLACK, RED, YELLOW, BLUE;

 public void run() {
   System.out.println("name()=" + name() +
       ", toString()=" + toString());
 }
}
A sample test program to invoke this run() method:
for(Color c : Color.values()) {
 c.run();
}
Or,
for(Runnable r : Color.values()) {
 r.run();
}
A more complete example with custom fields, constructors, getters, lookup method, and even a main method for quick testing:
import java.util.HashMap;
import java.util.Map;

public enum Status {
    PASSED(1, "Passed", "The test has passed."),
    FAILED(-1, "Failed", "The test was executed but failed."),
    DID_NOT_RUN(0, "Did not run", "The test did not start.");

    private int code;
    private String label;
    private String description;

    /**
     * A mapping between the integer code and its corresponding Status to facilitate lookup by code.
     */
    private static Map<Integer, Status> codeToStatusMapping;

    private Status(int code, String label, String description) {
        this.code = code;
        this.label = label;
        this.description = description;
    }

    public static Status getStatus(int i) {
        if (codeToStatusMapping == null) {
            initMapping();
        }
        return codeToStatusMapping.get(i);
    }

    private static void initMapping() {
        codeToStatusMapping = new HashMap<Integer, Status>();
        for (Status s : values()) {
            codeToStatusMapping.put(s.code, s);
        }
    }

    public int getCode() {
        return code;
    }

    public String getLabel() {
        return label;
    }

    public String getDescription() {
        return description;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("Status");
        sb.append("{code=").append(code);
        sb.append(", label='").append(label).append('\'');
        sb.append(", description='").append(description).append('\'');
        sb.append('}');
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(Status.PASSED);
        System.out.println(Status.getStatus(-1));
    }
}
To run the above example:
java Status

Status{code=1, label='Passed', description='The test has passed.'}
Status{code=-1, label='Failed', description='The test was executed but failed.'}

113 comments:

Shean said...

Seriously, this is a great post ;)

Been looking for almost 30min all over google for different enum examples and your single post showed them all, thanks alot ^^

Bhushan Bhangale said...

Good examples for understanding enum

Anonymous said...

This is an great INCORRECT post. Cannot do:

public enum Color {
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

private int code;

private Color(int c) {
code = c;
}

public int getCode() {
return code;
}
}

Anonymous said...

THIS IS SO CORRECT. IT WORKS FINE.
public enum Color {
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

private int code;

private Color(int c) {
code = c;
}

public int getCode() {
return code;
}
}

Marco Polo said...

This is a great incorrect post. You cannot say 'anonymous'. instead say your real name here.

Ramraj said...

Great post on java enums. Can you explain overriding methods inside enum variables or emum method. I dont any examples on this.

sihag said...

This is absolutely correct and help full post .....thank you very much for the post

Anonymous said...

Overriding enum example

public enum Element{

EARTH, WIND,
FIRE {
public String info() {
return "HOT";
}
};
public String info() {
return "element";
};

}

Anil Kumar Talla said...

Nice Info Thanks!!

ahmed.kamel said...

The example of implement interface and implement runnable (This example doesn't has any relation with threading) just explain the enum can implement any interface and this correct.
Thanks

Anonymous said...

Its wrong you need to have default construstor for Enums. Hence the original post may not compile.

Brian said...

You do not need a default constructor, please see: http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html

Anonymous said...

Enums are one of the few things that work with switch/case statements as well:

switch(db.getType()) // returns an enum element
{
case MYSQL: // no need to qualify names
...
case POSTGRES:
...
}

Dima said...

Thank you very much for this article!

Anonymous said...

It was owsumm :)

Anonymous said...

Very good post. Thanks.

Anonymous said...

Great post, thanks for it! =)

Anonymous said...

nice post .............

Anonymous said...

nice blog.
for java related material you can refer this link Click Here

Anonymous said...

Java is such a retarded language... like taking C++ and blowing its kneecaps off.

Anonymous said...

Very nice and self explanatory article, was reading quite a few article on it but this is best one.
@Ramraj
You can go over on these articles Enum Examples or Enum in java

Rony said...

Wonderful tutorial man. Thank you.

Anonymous said...

this is helpful

milan said...

More about Enum.
----------------
You cannot create Object of Enum type. It's objects are fixed.

public enum Color {
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

private int code;

private Color(int c) {
code = c;
}

public int getCode() {
return code;
}
}
In this example WHITE, BLACK,... are object of Enum type Color.

Thangavel L said...

Its a good example for understanding about the Enum.


Thanks keep on posting like this.

Sathish said...

It works great!

Anonymous said...

public enum Books {
MyBook, HisBook, YourBook;
};

class Test {
public static void main(String args[]) {
for(Books b : Books.values()) {
System.out.println(b);
System.out.println(b.ordinal());
}
}
}

This code compiles well. But when run generates "Exception in thread "main" java.lang.NoSuchMethodError: main".
What is the problem here?

javahowto said...

The Test class should be

public class Test {...}

Anonymous said...

Thank you very much...

It's easier to understand each usage... Thank you again...

Best of Android said...

Very useful examples. Thank you :)

Anonymous said...

Can you suggest me in a case where if i have a condition which consists of the following code

enum CoffeeSize
{
BIG(8),
HUGE(10),
OVERWHELMING(16)
{
public String getLidCode()
{
return "A";
}
};
CoffeeSize(int ounces)
{
this.ounces = ounces;
}
private int ounces;
public int getOunces()
{
return ounces;
}
public String getLidCode()
{
return "B";
}
}
Now how can i override this getLidCode() & get the Output in the Class.

Anonymous said...

really a nice post..............

NHarvey said...

You know what this is missing: How do you use the numbers to initialize an enum?
What I mean is, I have a direction enum:

<i style="font-family: Courier>
public enum Direction {
NORTH (0), EAST (90), SOUTH (180), WEST (270);
private int degrees;
Direction(int arg1) {
degrees=arg1;
}
}
</i>

And I want to be able to set certain variable of type Direction equal to 180 (for SOUTH). Is this possible, or can you only do that when you have strings in parentheses?

examinationtime said...

Very good post.
In short, Enum can have constructor, methods and inbuilt objects.

Anonymous said...

enum Bear
{
KF(100),RC(150),FO(200),TEN(),Two(10,20);
int price,x,y;
Bear(int x,int y)
{
this.x=x;
this.y=y;
price=x+y;
}
Bear(int price)
{
this.price=price;
}
Bear()
{
price=500;
}
public int getPrice()
{
return price;
}

}
class EnumDemo1
{
public static void main(String[] args)
{
Bear b1=Bear.KF;
System.out.println(b1+"--"+b1.price);
Bear b2[]=Bear.values();
for(Bear b3:b2)//enhanced for loop
{
System.out.println(b3+"----"+b3.getPrice());
}

}
}

Anonymous said...

what is difference b/w these two:

RED;
RED();

Sankar lp said...

The following are the compilation errors:
Enum types must not be declared abstract
To explicitly declare an enum type to be final.
To attempt to explicitly instantiate an enum type
To declare an abstract method within the enum constant body

Sankar.lp
Java Training

Mauricio said...

Thanks :)

Hasini Thamarasa said...

great.helpful post

Zaan said...

In this method:

public static Status getStatus(int i) {
if (codeToStatusMapping == null) {
initMapping();
}
Status result = null;
for (Status s : values()) {
result = codeToStatusMapping.get(i);
}
return result;
}

I do not see why you have a for loop. A hashmap is meant to facilitate the lookup in one go, and at the point where you do the get, it's supposedly filled correctly.

Am I missing something, or is the example imperfect?

javahowto said...

The for loop in getStatus(int) method is indeed not needed. It does the same, repetitive lookup multiple times. I've fixed it. Thanks for spotting it.

Anonymous said...

Good Tuto, Thanks ;

Becks said...

Genius post!

I've been inspired to give a more efficient version of the getStatus() function in the complex example.

Here goes:

private static Status[] statusArr; // only required member variable

public static Status getStatus(int i) {
if (statusArr == null) {
statusArr = Status.values();
}
return statusArr[i];
}

Anonymous said...

Who's there ?

Anonymous said...

Great post!

Anonymous said...

Beautiful and elegant.

Thanks for posting this.

Pieter Malan.

Anonymous said...

One of the best article to learn Enum. I would also suggest to read through following comprehensive 10 Enum Examples in Java and 15 Java Enum Interview Questions. Both of them provide good overview of different enum features.

Mallikarjuna said...

very much useful

David F said...

Becks said...
June 21, 2013 8:40 AM

In response to Becks post about "more efficient method" -- just wanted to point out to others that this only works if you let the ENUM values be assigned in order 0,1,2,3,4,5... In the example provided by the author, Becks solution would not work because it would check into an array with a "-1" value for example.

In summary, Becks optimization is only useful in limited circumstances. Happy coding!

java2novice said...

nice... for more java examples http://www.java2novice.com site

nabil said...

great post about enums, thanks a lot for the effort

nabil said...

great post about enums, thanks a lot

Nicolas COQUELET said...

In the complex example, usage of Hashmap cache access is an anti-pattern

1. Hashmap create useless memory overhead (hashmap has bad footprint)

2. hashmap get() isn't really efficient vs values loop

3. please stop to make small inefficient optimization, jvm do it for us

4. values() is more faster than map, try it ;)

-----------

public static Status getStatusWithoutMap(int i) {
for (Status s : values) {
if (s.code == i) {
return s;
}
}
return null;
}

public static void main(String[] args) {

long start = System.currentTimeMillis();

for (int i = 0; i < 100000; i++) {
Status.getStatusWithoutMap(25);
}
System.out.println((System.currentTimeMillis() - start) + "ms");

start = System.currentTimeMillis();

for (int i = 0; i < 100000; i++) {
Status.getStatus(25);
}

System.out.println((System.currentTimeMillis() - start) + "ms");
}


Porfirio Mendez Ocampo said...

Thanks bro...

tech blogger said...

awesome tips on java enum!

Expert4Assignment said...

this example also help you
public enum Color {
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

private int code;

private Color(int c) {
code = c;
}

public int getCode() {
return code;
}
}

Sawan Kumar said...

Split only after comma 3 times appear in Java

Question asked by my friend :
I have a string that looks like this:
0,0,1,2,4,5,3,4,6
What I want returned is a string[] that was split after every 3rd comma, so it would look like this:
[ "0,0,1", "2,4,5", "3,4,6" ]

JAVA J2EE Training in Chennai said...

Thanks for sharing such informative article on Java technology. It is most preferred technology among developers to create stunning mobile application fast and easy. It also created massive career opportunity for aspiring professionals. JAVA Training Institutes in Chennai

Answerz Answerz said...

Very Useful. For more examples visit http://answersz.com

Victoria John said...

Java is one of the popular technologies with improved job opportunity for hopeful professionals. Java Training in Chennai helps you to study this technology in details.

Victoria John said...

Thanks for sharing this informative blog.. If anyone want to get HTML5 Training in Chennai please visit FITA academy located at Chennai, Velachery. Rated as No.1 training and placement academy in Chennai.

kovalan Jayamurugan said...

Very post about Java spring batch is very useful to me. I tried your database creation code and its working great. Thanks for your informative post. This article is very useful for java professionals and students undergoing java training in Chennai.

Roshini Balu said...
This comment has been removed by the author.
Roshini Balu said...

tried this enum coding its work good thank you for this post, and its very useful for the fresher who wants to take a Java Training In Chennai

Roshini Balu said...

the enum concept what you have explained here is crystal clear thanks for sharing your post
JAVA J2EE Training Institutes in Chennai

jhansi joe said...


Thanks for sharing your view to our knowledge’s, its helps me plenty keep sharing…

JAVA Training in Chennai

Anonymous said...

Really a good post.Thank you very much.

Java Prime Number said...

Thanks for sharing good examples.

kovalan Jayamurugan said...

Thanks for sharing informative article on Node.js. In recent years, this technology is going to be the future of web design and development technology. I am going to include Node.js in my Web designing course in Chennai syllabus in educating my students.

karthik vijay said...

Thanks for sharing informative article!!! Your article helped me a lot to understand the importance of Best PHP Training in Chennai to secure lucrative job in web design and development industry.

Melisa said...

It was nice post, actually here i can learn the enumeration & its functions clearly, so keep sharing your updates regularly to improve my skills.
Regards,
Web designing course in chennai

dhanamlakshmi palu said...

Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing. Web desigining Training in chennai | Web desigining Training chennai | Web desigining course in chennai | Web desigining course chennai

Andrew Son said...

The information you have given here are most worthy for me. I have implemented in my training program as well, thanks for sharing.

Hadoop Training Chennai
Hadoop Training in Chennai

Arjun Rishi said...

Thank you for this wonderful tutorial. It was really helpful.

digital marketing institute

Arjun Rishi said...

Thank you for this wonderful tutorial. It was really helpful.

digital marketing institute

jhansi joe said...

Thanks of sharing this post…Python is the fastest growing language that helps to get your dream job in a best way, so if you wants to become a expertise in python get some training on that language.
Regards,
Python Training in Chennai|python training chennai|Python Course in Chennai

Roshini RS said...

The information you have deliver here is really useful to make my knowledge good. Thanks for your heavenly post. It is truly supportive for us and I have accumulated some essential data from this blog.
Regards,
Informatica training institute in Chennai|Best Informatica Training Institute In Chennai|Informatica training in chennai

Pooja Doss said...

Oracle DBA Training in Chennai
Thanks for sharing this informative blog. I did Oracle DBA Certification in Greens Technology at Adyar. This is really useful for me to make a bright career..

Pooja Doss said...

Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..
Websphere Training in Chennai

Pooja Doss said...

Data warehousing Training in Chennai
I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly..

Pooja Doss said...

Selenium Training in Chennai
Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

Pooja Doss said...

Oracle Training in chennai
Thanks for sharing such a great information..Its really nice and informative..

Pooja Doss said...


SAP Training in Chennai
This post is really nice and informative. The explanation given is really comprehensive and informative..

Pooja Doss said...

This information is impressive..I am inspired with your post writing style & how continuously you describe this topic. After reading your post,thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic
Android Training In Chennai In Chennai

Pooja Doss said...

Pretty article! I found some useful information in your blog, it was awesome to read,thanks for sharing this great content to my vision, keep sharing..
Unix Training In Chennai

Pooja Doss said...

I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
SalesForce Training in Chennai

Pooja Doss said...

There are lots of information about latest technology and how to get trained in them, like Best Hadoop Training In Chennai in Chennai have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies Hadoop Training in Chennai By the way you are running a great blog. Thanks for sharing this blogs..

Diya Patel said...

This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..
Informatica Training in chennai | QTP Training in Chennai



Neethu Sharma said...

Excellent information with unique content and it is very useful to know about the information based on blogs.
Hadoop Training In Chennai | oracle apps financials Training In Chennai | advanced plsql Training In Chennai

Neethu Sharma said...

I am very impressed with the article I have just read,so nice.......
QTP Training In Chennai | Selenium Training in Chennai | Oracle Training in Chennai

jhansi joe said...

I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
Regards,
Python Training in Chennai|Node JS training in chennai|cognos Training Chennai

Roshini Fita said...


Thanks for taking a time to discussing about this worth topic, it helps me a lot to improve my skill set. I would like see your updates , so keep blogging.
Regards,
sap training in Chennai|SAP Course in Chennai|SAP Training|SAP training in chennai |SAP course in chennai

caroline jesi said...


This data is magnificent. I am impressed with your writing style and how properly you define this topic, Thanks for sharing...
Regards,
ccna training in Chennai|ccna training institute in Chennai

Yasmin Priya said...

Thanks for sharing your ideas to our vision. It’s really useful for me. Selenium is an automation testing tool used for web applications. I did Selenium Training in Chennai at besant technologies. It’s useful for me to make a bright career in IT industry. For more details please visit our academy located at Chennai.

Yasmin Priya said...

Thanks for sharing your innovative ideas to our vision. I have read your blog and I gathered some new information through your blog. Your blog is really very informative and unique. Keep posting like this. Awaiting for your further update.
Thanks & Regards
Big Data Training in Chennai | Big Data Training in Chennai

Steve Smith said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions












Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

John Son said...

Hi, I am really happy to found such a helpful and fascinating post that is written in well manner. Thanks for sharing such an informative post. keep update your blog.
Regards.
Big Data Training in Chennai

Savitha said...

Great post and informative blog.it was awesome to read, thanks for sharing this great content to my vision.
Informatica Training In Chennai
Hadoop Training In Chennai
Oracle Training In Chennai
SAS Training In Chennai

Diya Patel said...

Best Java Training Institute In ChennaiThis information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..

Priya said...

Nice content. Software testing is the process of finding software bugs by executing program.
Software Testing Training in Chennai | Software testing course in Chennai | Fita Training

Harini said...

Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
Hadoop Training In Chennai

Priya said...

I have read this content it is very nice with unique information and keep updating us.
Digital Marketing Training in Chennai | digital marketing course in Chennai | FITA Velachery

Priya said...

Mobile application testing is the application software that is developed to handle hand held mobile devices. The testing in mobile application can be done by automated or manual type.
Mobile Application Testing Training in Chennai | mobile application testing | Appium Training in Chennai

Priya said...

Nice content. Software testing is the process of finding software bugs by executing program.
software testing training in chennai | software testing course in chennai| FITA Velachery

Cse It said...

I am highly thankful for this post. I’ve been looking everywhere for this! Thank kindness I found it on bloging effort. You’ve made my day! Thank you again!

sap ps online training
sap hana development online training
sap isu billing&invoice online training

khalid said...




MIDSUMMER SEASON WEDDING WEAR SHOES
Handbag & Clutches For Hot Girls
Front Open Double Shirt
Fashion Gallery Lehenga Choli
Stylo Best Mehndi Designs
HANDBAGS FOR WOMEN FASHION
Latest Sherwani Designs
Bridal Jewellery Set
Zara Shahjahan Eid Dresses
Mehndi Patterns for EID
SUMMER SEASON LADIES DRESSES FASHION
Sophia Tolli Collection
Earrings In Gold Collection
Actress Maya Ali – Fashion Collection
Bridal Gowns Collection
LADIES BLAZER STYLES OUTFITS
MEHNDI DRESS DESIGNS
BRIDAL SHOES
SHIRTS GRAY MAXI SKIRT SKIRTS
BRIDAL DRESSES WESTERN STYLE
LAWN AND CHIFFON OUTFITS
classic lawn suits
mix eid dresses
midsummer kurta
anarkali suits

khalid said...

REVLON NAIL POLISH COLORS
lehnga choli dresses
bridal makeup
ball garments
babydoll night wear dresses
MEN WEAR WEDDING SHERWANI
Jewelry Women Wear
Saheli Couture By Preity Zinta Dresses
Parties Hairstyle
Zainab Chottani Pretty Suits
STYLISH SUNGLASSES DESIGNS
FROCKS DESIGNS FASHION
LONG GOWNS OUTFITS FASHION
HUMAN SALMAN KHAN STYLISH DRESSES
UTSAV FASHION NET INDIAN SAREES
Fancy Lawn Clothes
Nail Designs For UK Girls
Girls Footwear Selection
Pakistani Lehenga Clothes

hadoop training in chennai said...

Hi,I will be learning that the lot of new information.
hadoop training in chennai | informatica training in chennai

Nikshitha S said...
This comment has been removed by the author.
Nikshitha S said...

PHP provides the best option to build the website where we can design our website in a very interactive manner that provides better functioning in data management.
PHP Training in Chennai | PHP course in Chennai

Best Multimedia (Dilsukhnagar Arena) said...

good blog...web design course

Reeta said...

Yes, you are absolutely correct...And it is very informative and very clear and easy to understand.. seo training in chennai

Nikshitha S said...

The strategy you have posted on this technology helped me to get into the next level and had lot of information in it. The angular js programming language is very popular which are most widely used.
Angularjs Training in Chennai | Angularjs training Chennai