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.'}

61 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

Anu Priya said...

This a great post about Java Enums. Excellent clarification, thanks!
HTML institute in Chennai

Anu Priya said...
This comment has been removed by the author.
Answerz Answerz said...

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