Pages

What is Enum in Java Enum in Javais a keyword, a feature which is used to represent fixed number of well-known values in Java, For example, Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Generics, varargs and static import. One of the common use of Enum which emerged in recent years is Using Enum to write Singleton in Java, which is by far easiest way to implement Singleton and handles several issues related to thread-safety and Serialization automatically. By the way, Java Enum as a type is more suitable to represent well known fixed set of things and state, for example representing the state of Order as NEW, PARTIAL FILL, FILL or CLOSED. Enumeration(Enum) was not originally available in Java though it was available in another language like C and C++, but eventually, Java realized and introduced Enum on JDK 5 (Tiger) by keyword Enum. In this Java Enum tutorial, we will see different Enum example in Java and learn using Enum in Java. Focus of this Java Enum tutorial will be on different features provided by Enum in Java and how to use them. If you have used Enumeration before in C or C++ then you will not be uncomfortable with Java Enum but in my opinion, Enum in Java is more rich and versatile than in any other language. By the way, if you like to learn new concepts using book then you can also see Head First Java 2nd Edition, I had followed this book while learning Enum, when Java 1.5 was first launched. This book has excellent chapter not only on Enum but also on key features of Java 1.5 and worth reading.

How to represent enumerable value without Java enum

Since Enum in Java is only available from Java 1.5 it's worth to discuss how we used to represent enumerable values in Java prior JDK 1.5 and without it. I use public static final constant to replicate enum like behavior. Let’s see an Enum example in Java to understand the concept better. In this example, we will use US Currency Coin as enumerable which has values like PENNY (1) NICKLE (5), DIME (10), and QUARTER (25).

1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to currency e.g. 99 though there is no coin to represent that value.

2) No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"

3) No namespace: to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5

Java Enum is the answer of all this limitation. Enum in Java is type-safe, provides meaningful String names and has their own namespace. Now let's see the same example using Enum in Java:

publicenumCurrency {PENNY, NICKLE, DIME, QUARTER};

Here Currency is our enum and PENNY, NICKLE, DIME, QUARTER are enum constants. Notice curly braces around enum constants because Enum is a type like class and interface in Java. Also, we have followed the similar naming convention for enum like class and interface (first letter in Caps) and since Enum constants are implicitly static final we have used all caps to specify them like Constants in Java.

What is Enum in Java

Now back to primary questions “What is Enum in java” simple answer Enum is a keyword in java and on more detail term Java Enum is a type like class and interface and can be used to define a set of Enum constants. Enum constants are implicitly static and final and you can not change their value once created. Enum in Java provides type-safety and can be used inside switch statement like int variables. Since enum is a keyword you can not use as a variable name and since its only introduced in JDK 1.5 all your previous code which has an enum as a variable name will not work and needs to be refactored.

Benefits of using Enums in Java

1) Enum is type-safe you can not assign anything else other than predefined Enum constants to an Enum variable. It is a compiler error to assign something else, unlike the public static final variables used in Enum int pattern and Enum String pattern.

2) Enum has its own namespace.

3) The best feature of Enum is you can use Enum in Java inside Switch statement like int or char primitive data type. We will also see an example of using java enum in switch statement in this java enum tutorial.

4) Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.

Important points about Enum in Java

1) Enums in Java are type-safe and has their own namespace. It means your enum will have a type for example "Currency" in below example and you can not assign any value other than specified in Enum Constants.

2) Enum in Java are reference types like class or interfaceand you can define constructor, methods and variables inside java Enum which makes it more powerful than Enum in C and C++ as shown in next example of Java Enum type.

3) You can specify values of enum constants at the creation time as shown in below example:

publicenumCurrency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};

But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value, see below example.

The constructor of enum in java must be privateany other access modifier will result in compilation error. Now to get the value associated with each coin you can define a public getValue() method inside Java enum like any normal Java class. Also, the semicolon in the first line is optional.

4) Enum constants are implicitly static and final and can not be changed once created. For example, below code of java enum will result in compilation error:

Currency.PENNY=Currency.DIME;

The final field EnumExamples.Currency.PENNY cannot be reassigned.

5) Enum in java can be used as an argument on switch statement and with "case:" like int or char primitive type. This feature of java enum makes them very useful for switch operations. Let’s see an example of how to use java enum inside switch statement:

If you are not convinced than you should read this article to learn more about pros and cons of comparing two enums using equals() vs == operator in Java.

7) Java compiler automatically generates static values() method for every enum in java. Values() method returns array of Enum constants in the same order they have listed in Enum and you can use values() to iterate over values of Enum in Java as shown in below example:

9) Two new collection classes EnumMapand EnumSetare added into collection package to support Java Enum. These classes are a high-performance implementation of Map and Set interface in Java and we should use this whenever there is any opportunity.

EnumSet doesn't have any public constructor instead it provides factory methods to create instance e.g. EnumSet.of() methods. This design allows EnumSet to internally choose between two different implementations depending upon the size of Enum constants.

If Enum has less than 64 constants than EnumSet uses RegularEnumSet class which internally uses a long variable to store those 64 Enum constants and if Enum has more keys than 64 then it uses JumboEnumSet. See my article the difference between RegularEnumSet and JumboEnumSet for more details.

11) An instance of Enum in Java is created when any Enum constants are first called or referenced in code.

12) Enum in Java can implement the interface and override any method like normal class It’s also worth noting that Enum in java implicitly implements both Serializable and Comparable interface. Let's see and example of how to implement interface using Java Enum:

13) You can define abstract methods inside Enum in Java and can also provide a different implementation for different instances of enum in java. Let’s see an example of using abstract method inside enum in java

In this example since every coin will have the different color we made the color() method abstract and let each instance of Enum to define their own color. You can get color of any coin by just calling the color() method as shown in below example of Java Enum:

System.out.println("Color: "+Currency.DIME.color());

So that was the comprehensive list of properties, behavior and capabilities of Enumeration type in Java. I know, it's not easy to remember all those powerful features and that's why I have prepared this small Microsoft powerpoint slide containing all important properties of Enum in Java. You can always come back and check this slide to revise important features of Java Enum.

Real world Examples of Enum in Java

So far you have learned what Enum can do for you in Java. You learned that enum can be used to represent well known fixed set of constants, enum can implement interface, it can be used in switch case like int, short and String and Enum has so many useful built-in metods like values(), vlaueOf(), name(), and ordinal(), but we didn't learn where to use the Enum in Java? I think some real world examples of enum will do a lot of good to many pepole and that's why I am going to summarize some of the popular usage of Enum in Java world below. Enum as Thread Safe SingletonOne of the most popular use of Java Enum is to impelment the Singleton design pattern in Java. In fact, Enum is the easieset way to create a thread-safe Singleton in Java. It offer so many advantage over traditional implementation using class e.g. built-in Serialization, guarantee that Singleton will always be Singleton and many more. I suggest you to check my article about Why Enum as Singelton is better in Java to larn more on this topic. Strategy Pattern using Enum
You can also implement the Strategy design pattern using Enumeration type in Java. Since Enum can implement interface, it's a good candidate to implement the Strategy interface and define individual strategy. By keeping all related Strategy in one place, Enum offer better maintainence support. It also doesn't break the open closed design principle as per se because any error will be detected at compile time. See this tutorial to learn how to implement Strategy pattern using Enum in Java.

Enum as replacement of Enum String or int pattern
There is now no need to use String or integer constant to represent fixed set of things e.g. status of object like ON and OFF for a button or START, IN PROGRESS and DONE for a Task. Enum is much better suited for those needs as it provide compile time type safety and better debugging assistent than String or Integer.

Enum as State Machine
You can also use Enum to impelment State machine in Java. A State machine transition to predifine set of states based upon current state and given input. Since Enum can implement interface and override method, you can use it as State machine in Java. See this tutorial from Peter Lawrey for a working example.

Enum Java valueOf example
One of my readers pointed out that I have not mentioned about the valueOf method of enum in Java, which is used to convert String to enum in Java.

Here is what he has suggested, thanks @ Anonymous

“You could also include valueOf() method of enum in java which is added by compiler in any enum along with values() method. Enum valueOf() is a static method which takes a string argument and can be used to convert a String into an enum. One think though you would like to keep in mind is that valueOf(String) method of enum will throw "Exception in thread "main" java.lang.IllegalArgumentException: No enum const class" if you supply any string other than enum values.

Another of my reader suggested about ordinal() and name() utility method of Java enum Ordinal method of Java Enum returns the position of a Enum constant as they declared in enum while name()of Enum returns the exact string which is used to create that particular Enum constant.” name() method can also be used for converting Enum to String in Java.

That’s all on Java enum, Please share if you have any nice tips on enum in Java and let us know how you are using java enum in your work. You can also follow some good advice for using Enum by Joshua Bloch in his all time classic book Effective Java. That advice will give you more idea of using this powerful feature of Java programming language

Further Reading on Java Enum

If you like to learn more about this cool feature, I suggest reading following books. Books are one of the best resources to completely understand any topic and I personally follow them as well. Enumeration types chapter from Thinking in Java is particularly useful.

60 comments
:

Nice! I use enum regulary, but I didn't know it is so versatile. Thank you very much for this complete summary.

One more thing - beware overuse of enum. Right now I'm refactoring a project, where programmer used enum for defining colors used in application (including their names), but now management wants to sell this application abroad and now I have to remove this enum and put these information into database.

you could also include valueOf() method of enum in java which is added by compiler in any enum along with values() method. enum valueOf()is a static method which takes a string argument and can be used to convert a String into enum. One think though you would like to keep in mind is that valueOf(String) method of enum will throw "Exception in thread "main" java.lang.IllegalArgumentException: No enum const class" if you supply any string other than enum values.

dude how can you miss ordenal() and name() method of enum in java. Ordinal method of java enumo returns position of a enum constant as they declared in enum while name()of enum returns the exact string which is used to create that particular enum constant.

One of the most Complete tutorial I have read on Java Enum, didn't know that Enum in Java is this much versatile and we can do all this stuff with enum. I am going to recommend this article to all my students for Java Enum, I also want to distribute printed copy of this Java enum tutorial, let me know if its ok to you. Thanks.

is there any difference in Java Enum in Java5 and Java6 ? is functionality of Enum in Java has enhanced in JDK 1.6 ?We are going to use Java6 in our application and would like to know if there is any significant change on Enum in Java6. Thanks

Hi Can you please post example of Converting String to Enum in Java and opposite i.e. How to convert Enum to String in Java. we have an application where we need to convert from enum to string and vice-versa and I am looking for quick way of converting that. thanks

I am trying to use Enum in Switch case but getting this error "an enum switch case label must be the unqualified name of an enumeration constant", Looks like Enum in Switch are not allowed or only allowed with some restriction, Can you please help.about Code its simple WEEKDAY Enum with switch on every day.

Best Tutorial on Enum in Java I have read. Indeed extensive and shows how differently one can use Enum in Java you could have also included EnumMap and EnumSet which are specifically optimized for Enums and much faster than there counterparts.

Excellent tutorial and example on Enum in Java.most extensive and useful coverage I have seen on Java 5 Enum.I would add on this on advantages of Java Enum. Though I see you have already described some benefits of Enum, mentioning some more advantages of Enum will certainly help:

1) Enum in Java is Type or you can say a Class.2) Enum can implement interfaces.3) You can compare two Enum without worrying about comparing orange with apples.4) You can iterate over set of Enums.

I was looking for an example of How to use Enum in Switch Case, when I found this tutorial. this shows many ways we can use Enum in Java, never thought of iterating all Enums in a for loop, Enum extending interface, enum overriding methods. I was only thinking enum in terms of fixed number of well know values but Java enum is way beyond that. Its full featured abstraction like Class. Now after reading your article my question why can't we use Enum in place of Class ? I expect we may not able to use Enum in every place but there must be certain cases where Enum in Java is more appropriate to Class.

EnumMap does not allow null value for keys.If you try to put null as key in an EnumMap you will get an NullPointerException If you want to declare an enumMap with generics note that you should declare your key as > EnumMap's implementation uses an array and for that reason has slightly better performance than HashMaps

One of the better example of Enum in Java API is java.util.concurrent.TimeUnit class which encapsulate Time conversion and some utility method related to time e.g. sleep. TimeUnit is an Enum it also implement several methods.

@Tutorials, Currency denomination which is Enum is final constants e.g. 100 , 10 or 5 etc. Currency variable which is int in case of enum int pattern can point out any valid int values instead of valid Currency value. Because Compiler doesn't throw compile time error in case of enum int pattern, its not type safe but in case Currency is Enum you can only assign valid Currency denomination which is Enum instances or constants.

Hi Javin,Gr8 article few things I want to add to simplify the things , Please let me know what is your point of view on this below understandings..!!

You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: "permanent", "temp", "apprentice"), or flags ("execute now", "defer execution").

If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.

BTW, overuse of enums might mean that your methods do too much (it's often better to have several separate methods, rather than one method that takes several flags which modify what it does), but if you have to use flags or type codes, enums are the way to go.

/** Counts number of foobangs. * @param type Type of foobangs to count * @return number of foobangs of type */public int countFoobangs(FB_TYPE type)In the second example, it's immediately clear which types are allowed, docs and implementation cannot go out of sync, and the compiler can enforce this.

@Marton, You are absolutely right on that toString() should return a String, instead of printing. This is more for demonstration purpose, any of those switch cases can return String equivalent of enum, instead of a call to super.enum at bottom.

Another good example of enum from JDK is ThreadState enum, which is official guide on different thread state. This enum describe all possible thread states e.g. NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING etc, and removes lot of confusion around thread state. This is also an example of where to use Enum, Surely using it to represent state is one of the best usecase.

OMG...im loving each nd every tutorial of urs..simple, neat, clear. Better u write a book. I think u r d only admin who takes the comments given by readers seriously nd incorporates them in ur posts :) hats off to u... keep blogging. u hv great fan following

It's final, so you cannot adapt it to your needs. If you want them to start with 1 - not possible. If you want one number not to be used (eg because you removed a value from your enum and you do not want the old ordinals to change), you have a problem.

If you need an arbitrary numeric representation of your values, you should consider providing your own method instead of using ordinal().

Hey, I have a question, Can one Enum extends another Enum in Java? is it possible to declare Enum using extends clause? This was asked to me in a Java interview. Since enum is neither class nor interface, I find it tricky, but as you said Enum can implement interface, I am assuming it can also extend another class or enum?

WOW, lots of examples from Enum. Great works guys, including Commentators. Here is one of my Enum examples. It's from financial worlds. We have a clearer, normally banks, which clears trades and charge clearing fees ranging form $100- $500. If you are dealing with only few clearer, you can use Enum to represent them as shown below :

@Anonymous, both are Ok, until you have less number of enum constant. switch result in concise code (less number of lines, hence more readable) and overriding toString inside each is like open closed principle but takes more space.

Nice article..Thank you dear...1. You mentioned "Also, the semicolon in the first line is optional." but semicolon is optional only if enum has only well defined constants but if we miss semicolon when it has other members like methods then we must have semicolon.2. If enum has other members other than constants then constants must be at 1st line inside a enum else compiler will throw an exception..hope it helps.Thank u once again:)