Tuesday, August 31, 2021

Java Enum Tutorial: 10 Examples of Enum in Java

What is Enum in Java
Enum in Java is a keyword, a feature that is used to represent a fixed number of well-known values in Java, For example, Number of days in the Week, Number of planets in the 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 the 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 states,  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++, 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. The 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 a 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 an excellent chapter not only on Enum but also on key features of Java 1.5 and is worth reading.





How to represent enumerable value without Java enum

java enum example, enum in java tutorialSince Enum in Java is only available from Java 1.5 it's worth discussing how we used to represent enumerable values in Java prior to JDK 1.5 and without it. I use a 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).

public class CurrencyDenom {
   public static final int PENNY = 1;
   public static final int NICKLE = 5;
   public static final int DIME = 10;
   public static final int QUARTER = 25;
}

public class Currency {
   private int currency; //CurrencyDenom.PENNY,CurrencyDenom.NICKLE,
                         // CurrencyDenom.DIME,CurrencyDenom.QUARTER
}

 Though this can serve our purpose it has some serious limitations:

 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 constants will print its numeric value instead of the 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 these limitations. 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:

public enum Currency {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 a 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 in 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 statements like int variables. 

Since enum is a keyword you can not use as a variable name and since it's 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 the 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 statements like int or char primitive data type. We will also see an example of using java enum in the 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 have their own namespace. It means your enum will have a type for example "Currency" in the below example and you can not assign any value other than specified in Enum Constants.
 
public enum Currency {
PENNY, NICKLE, DIME, QUARTER
};
Currency coin = Currency.PENNY;
coin = 1; //compilation error  


2) Enum in Java are reference types like class or interface and 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 the below example:


public enum Currency {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 that accepts int value, see the below example.
  
public enum Currency {
        PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
        private int value;

        private Currency(int value) {
                this.value = value;
        }
};  

The constructor of the enum in java must be private any other access modifier will result in a 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, the below code of java enum will result in a 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:  

 Currency usCoin = Currency.DIME;
    switch (usCoin) {
            case PENNY:
                    System.out.println("Penny coin");
                    break;
            case NICKLE:
                    System.out.println("Nickle coin");
                    break;
            case DIME:
                    System.out.println("Dime coin");
                    break;
            case QUARTER:
                    System.out.println("Quarter coin");
 }
  
from JDK 7 onwards you can also String in Switch case in Java code.


6) Since constants defined inside Enum in Java are final you can safely compare them using "==", the equality operator as shown in the following example of  Java Enum:

Currency usCoin = Currency.DIME;
if(usCoin == Currency.DIME){
  System.out.println("enum in java can be compared using ==");
}

By the way comparing objects using == operator is not recommended, Always use equals() method or compareTo() method to compare Objects.

If you are not convinced then you should read this article to learn more about the 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 an 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 the below example:

for(Currency coin: Currency.values()){
   System.out.println("coin: " + coin);
}

And it will print:
coin: PENNY
coin: NICKLE
coin: DIME
coin: QUARTER
               
Notice the order is exactly the same as the defined order in the Enum.



8) In Java, Enum can override methods also. Let’s see an example of overriding the toString() method inside Enum in Java to provide a meaningful description for enums constants.

public enum Currency {
  ........
      
  @Override
  public String toString() {
       switch (this) {
         case PENNY:
              System.out.println("Penny: " + value);
              break;
         case NICKLE:
              System.out.println("Nickle: " + value);
              break;
         case DIME:
              System.out.println("Dime: " + value);
              break;
         case QUARTER:
              System.out.println("Quarter: " + value);
        }
  return super.toString();
 }
};        

And here is how it looks like when displayed:


Currency usCoin = Currency.DIME;
System.out.println(usCoin);

Output:
Dime: 10


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

EnumSet doesn't have any public constructor instead it provides factory methods to create instances 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 then 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 on the difference between RegularEnumSet and JumboEnumSet for more details.




10) You can not create an instance of enums by using a new operator in Java because the constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.


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 a normal class It’s also worth noting that Enum in java implicitly implements both Serializable and Comparable interfaces. Let's see an example of how to implement the interface using Java Enum:

public enum Currency implements Runnable{
  PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
  private int value;
  ............
        
  @Override
  public void run() {
  System.out.println("Enum in Java implement interfaces");
                
   }
}


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

 public enum Currency {
        PENNY(1) {
            @Override
            public String color() {
                return "copper";
            }
        },
        NICKLE(5) {
            @Override
            public String color() {
                return "bronze";
            }
        },
        DIME(10) {
            @Override
            public String color() {
                return "silver";
            }
        },
        QUARTER(25) {
            @Override
            public String color() {
                return "silver";
            }
        };
        private int value;

        public abstract String color();

        private Currency(int value) {
            this.value = value;
        }
 
}     

In this example since every coin will have a different color we made the color() method abstract and let each instance of Enum define its own color. You can get the color of any coin by just calling the color() method as shown in the 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.

Java Enum tutorial and examples


 


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 an interface, it can be used in switch cases like int, short and String and Enum has so many useful built-in methods like values(), the valueOf(), 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 people and that's why I am going to summarize some of the popular usages of Enum in the Java world below. 


Enum as Thread Safe Singleton
One of the most popular uses of Java Enum is to implement the Singleton design pattern in Java. In fact, Enum is the easiest way to create a thread-safe Singleton in Java. It offers so many advantages over traditional implementation using class e.g. built-in Serialization, guarantee that Singleton will always be Singleton, and many more. I suggest you check my article about Why Enum as Singelton is better in Java to learn more on this topic. 


Strategy Pattern using Enum
You can also implement the Strategy design pattern using the Enumeration type in Java. Since Enum can implement an interface, it's a good candidate to implement the Strategy interface and define individual strategy. 

By keeping all related Strategies in one place, Enum offers better maintenance 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 patterns 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 a fixed set of things e.g. status of an 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 provides compile-time type safety and a better debugging assistant than String or Integer.


Enum as State Machine
You can also use Enum to implement a State machine in Java. A State machine transitions to a predefined set of states based upon the current state and given input. Since Enum can implement an interface and override method, you can use it as a 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 the valueOf method of enum in Java, which is used to convert String to enum in Java.

Here is what he has suggested, thanks to @ 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 an 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 an 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 the Java programming language

5 Best Core Java Courses for Beginners


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

Java Enum examples
  • Thinking in Java (4th Edition) By Bruce Eckel
  • Effective Java by Joshua Bloch
  • Java 5.0 Tiger: A Developers notebook
  • Java 7 Recipes
The last book is suggested by one of our readers @Anonymous, you can see his comment
Check out the book, Java 7 Recipes. Chapter 4 contains some good content on Java enums. They really go into depth and the examples are excellent.





66 comments :

Jirka Pinkas said...

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.

Anonymous said...

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.

Anonymous said...

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.

Anonymous said...

Can you write about reverse lookup using Enum in Java ? I am not able to understand that concept which is an important usage of java enum. thanks

R. RamaKashyap said...

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.

Anonymous said...

Thank you for this tutorial, i've found it very helpful!

Ram said...

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

Javin @ String split Java example said...

@Ram, As such I don't see any difference on Enum from Java5 to Java6. and you can safely use them on Java6.

Gyananedra said...

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

Taner said...

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.

Anonymous said...

@Taner: It's just a guess (since you didn't provide any details), but apparently you're using qualified names in the case label.
i.e.
case Weekday.MONDAY:
instead of
case MONDAY:

i think you can't mix enums. and it would be very messy if you're always prepending the enum name

Anonymous said...

Nice one

Anonymous said...

Please provide EnumMap and EnumSet

Anonymous said...

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.

Anonymous said...

Can we declare two constructors for enum. If we can how can we access that?

Mansi said...

Another useful example of Enum in Java is using Enum for writing Thread-safe Singleton. its pretty easy and handles all thread-safety concern inherently:

public enum SINGLETON{
INSTANCE;
}

Anonymous said...

hi this was more useful, i have some problems with my java program, i will post it late if any one could help thank you..

Sushil said...

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.

In short flexibility and power is biggest advantage of Java Enum.

Gesu said...

I have few interview questions related to Enum in Java, I hope you all help me to find answers:

Can one Enum extends another Enum in Java? or Can Enum extends another Class in Java ?

Can Enum implement interfaces in Java? if yes how many ?

Javin @ spring interview questions said...

@Dinesh, Glad to hear that you like this Java enum tutorial. Enum is more useful than just for storing enumeration values and this can be used in variety of Java programs.

Satya said...

Constructor of enum in java must be private

i think it works with default also

Robin said...

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.

Anonymous said...

Some things that are good to remember about enumMaps are:

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

Anonymous said...

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.

Puskin said...

How to use Enum in Switch without using values method ? I want to switch on Enum where case can be individual Enum instances e.g.

switch(Button){
case Button.ON :
break;
case Button.OFF:
break;
}
Does this is a legal example of using Enum in Switch and case statement ?

Tutorials said...

I guess below statement is wrong,

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.

Because values has been taken with 'final'.so, how can we change once it is created ?



Javin @ CyclicBarrier Example Java said...

@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.

Srinivas said...

Nice articles..

Anonymous said...

enum CoffeeSize{ BIG,HUGE,LARGE} ;

CoffeeSize cs=CoffeeSize.HUGE;
cs=CoffeeSize.LARGE;

i have tested above code on java6+ netbean7.2 it's working but it's contradict with the following

"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 re assigned."

Donald Arthur Kronos - Actor said...

Anonymous, Nov 29: That example....

enum CoffeeSize{ BIG,HUGE,LARGE} ;

CoffeeSize cs=CoffeeSize.HUGE;
cs=CoffeeSize.LARGE;

... is not reassigning a constant or final field, such as CoffeeSize.Large but rather reassigning the variable cs of enum type CoffeeSize.

Donald Kronos

Anonymous said...

Here is an alternative way to storing additional information associated with each enum constant:
//First the enum:
enum Days {
MONDAY ("Lundi", "Montag", "indu vasaram"),
TUESDAY ("Mardi", "Dienstag", "bhauma vasaram"),
WEDNESDAY ("Mercredi", "Mittwoch", "saumya vasaram"),
THURSDAY ("Jeudi", "Donnerstag", "guru vasaram"),
FRIDAY ("Vendredi", "Freitag", "bhrgu vasaram"),
SATURDAY ("Samedi", "Samstag", "sthira vasaram"),
SUNDAY ("Dimanche", "Sonntag", "bhanu vasaram");

String inFrench;
String inGerman;
String inSanskrit;
Days(String inFrench, String inGerman, String inSanskrit)
{
this.inFrench = inFrench;
this.inGerman = inGerman;
this.inSanskrit = inSanskrit;
}
}
//Now an app to use the enum:
public class DaysTest {

public static void main(String[] args) {
System.out.println("\nDays of the week in Sanskrit:");
for (Days d : Days.values())
{
System.out.println( d.inSanskrit);

}
}
}
Thanks and regards,
Steve

Anonymous said...

Hi Javin,
Sorry -- forgot to mention:
Excellent tutorial!
Thank you also other commentors for your information.

Regards,
Steve

SARAL SAXENA said...

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.

As an example, which is better?

/** Counts number of foobangs.
* @param type Type of foobangs to count. Can be 1=green foobangs,
* 2=wrinkled foobangs, 3=sweet foobangs, 0=all types.
* @return number of foobangs of type
*/
public int countFoobangs(int type)
versus

/** Types of foobangs. */
public enum FB_TYPE {
GREEN, WRINKLED, SWEET,
/** special type for all types combined */
ALL;
}

/** 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.

SARAL SAXENA said...

@Gesu yeah Nice questions you have asked here the solution for your first question ..

Q1) Can one Enum extends another Enum in Java? or Can Enum extends another Class in Java ?

No, you can't. If you look at the definition of Enum, instances of it are final and can't be extended. This makes sense if you understand enums as a finite, final set of values.

No it's not possible. The best you can do is make two enums implement and interface and then use that interface instead of the enum. So:

interface Digit {
int getValue();
}

enum Decimal implements Digit {
ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE;

private final int value;

Decimal() {
value = ordinal();
}

@Override
public int getValue() {
return value;
}
}

enum Hex implements Digit {
A, B, C, D, E, F;

private final int value;

Hex() {
value = 10 + ordinal();
}

@Override
public int getValue() {
return value;
}
}

Unknown said...

In the 8th example the implementation of toString() is very wrong. A toString() method should not print anything to System.out, but instead return all that information as a String.

Javin @ Sort Hashtable on values in Java said...

@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.

suresh said...

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.

Anonymous said...

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

m2wester said...

You should be carefull using ordinal().

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().

Harry said...

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?

Anonymous said...

Is there any change on Enum in Java 6, Java 7 or even expecting change in java 8 ?

James said...

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 :

private enum Clearer{
BankOfAmerica(new BigDecimal(300)), Citibank(new BigDecimal(300)), Goldman(new BigDecimal(300));

private BigDecimal clearingCharge; //in dollars

private Clearer(BigDecimal fees){
this.clearingCharge = fees;
}

public BigDecimal getClearningCharge(){
return clearingCharge;
}
}

getClearingCharge() method is a nice convenient way to get clearing fees.

Anonymous said...

Can we use abstract keyword along with Enum in Java? I want to use abstract method with enum, how to use that?

Anonymous said...

Just to add my 2 cents on this wonderful article on Enum, I would like to share few tips on when to use Enum in Java programs :

1) Prefer Enum over String, for example if your method accepts String argument, which you compare against predefined one, than consider passing Enum, it will provide compile time type safety.

2) Prefer Enum over integer constant, Similar to reasons mentioned above, if you are accepting int and comparing with constants, consider accepting Enum.

3) Consider Enum for passing choices and options by wrapping Enum constants inside EnumSet e.g. EnumSet.of(Choice.ONE, Choice.TWO)

4) You can even implement Strategy design pattern and State design Pattern using Enum in Java.

Cheers

Anonymous said...

constructor of enum need not to be private check it
once

Sourabh said...

Read many article on Enum but was never clarified until i read your blog.Its very nice and crisp thnks for shring it in very simple way,helped me a lot to know the versatility of Enum in Java

Unknown said...

yes constructor in enum need not to be private.

Unknown said...

Constructor in enum need not be emply...Anonymous is right...anyway this tutorial is really nice. please make tutorial related to thread also.

Anonymous said...

you are a brave java developer...for this(Further Reading on Java Enum...)

Unknown said...

The awesomest explanation ever. It is so detailed and very well explained. Thanks a ton!

Anonymous said...

Is it mandatory to make constructor of enum as private

Anonymous said...

You have written that constructors of enum type can only be private...
But I have read on docs.orale.com that, it can be private or package-private
.
.
Can you please re-confirm this

Unknown said...

Thanks,
It's make sense

Anonymous said...

You should avoid switching within the enum. So the same enum with a better toString would be:
public enum Currency {
PENNY(1) {
@Override
public String toString() {
return "Penny: " + super.value;
}
},
NICKLE(5) {
@Override
public String toString() {
return "Nickle: " + super.value;
}
},
DIME(10) {
@Override
public String toString() {
return "Dime: " + super.value;
}
},
QUARTER(25) {
@Override
public String toString() {
return "Quarter: " + super.value;
}
};

private final int value;

private Currency(int value) {
this.value = value;
}

public static void main(String[] args) {
System.out.println(QUARTER);
}
}

javin paul said...

@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.

Unknown said...

Very good Article. Thanks for this :)

GOPI said...

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:)

javin paul said...

Good points @GOPI, well done !!

Anonymous said...

Very very informative article, and also thanks users for great comments

Amol said...

public enum FormOfPayment {
BILLBACK(), BILLBAKC2(),BILLBACK3()
}

What does empty bracket means here?

javin paul said...

Hello Amol, that empty bracket mean call to a no-argument constructor. Since enum can have constructor, you can also call them like that e.g. BILLBACK("bill") means call to a constructor which takes one String argument. I have shown examples of Enum with constructor in this article already.

You can also further check that by adding a no-argument constructor and printing something from it e.g.

public enum FormOfPayment {
BILLBACK(), BILLBAKC2(),BILLBACK3();

FormOfPayment(){
System.out.println("Hello");
}
}

Anonymous said...

enum Season {
SUCCESS(),
FAILURE() ;
Season(){
System.out.println("Hello enum");
}
}
class EnumExample3{
public static void main(String[] args) {
//System.out.println(Season.SUCCESS);
Season.SUCCESS; // this line of code give an error: not a statement
}}

// why the commented out line of code giving error while commented in code is //running

javin paul said...

Hello Arshad, the error is because just writing value is illegal e.g. 5; you need to store the value into a variable e.g.
Season s = Season.SUCCESS;
this will solve the error.

Ganesh said...

Nice and very clear explanation

Wali said...

This is a really good write up on enums, clear and to the point. This article must've been updated at some point, but it's still relevant and useful.

javin paul said...

Hello Wali, glad that you like this Enum tutorial, Yes, I try to regularly update my articles. I also thankful to my readers which point out and alert for any information which needs to be update.

Post a Comment