Pages

A Practical Example of Enum in Java

Enum is a useful feature of Java and the best way to represent fixed number of things e.g. a number of the planet in the solar system, the number of state order can be or simply a number of days in a week. Java Enum is different than their predecessor on other languages like C and C++, where the enum is just a wrapper around integer constant. Enum in Java is a full blown type like class and interface, they can have constructor (though only private constructors are permitted for Enum), they can override methods, they can have member variables, they can even declare methods, can implement interfaces and have specialized high performance Map and Set implementation in form of EnumMap and EnumSet. I have written a lot of articles in Enum, exploring it's different lesser known features and involving some best practices, but several times I receive a request for simple Enum examples, and that's why, I am sharing this, one of the most simple examples of Enum in Java. In this Enum example, I have used Enum to represent SoftDrink in a convenience store. This Enum class has four types of soft drinks Coke, Pepsi, Soda, and Lime. To demonstrate Enum can have constructor and member variables, I have provided them title and price, and to demonstrate Enum can override methods, I have overridden toString() method, which returns custom title passed to each SoftDrink. Apart from the custom title, you can also avail implicit name() method of Enum to get a String representation of Enum constant, it returns exact String literal used to declare Enum constant, for example, SoftDrink.COKE.name() will return COKE while SoftDrink.COKE.toString() will return Coke here.

Here is some important points about Enum in Java, which is worth remembering as well:

Let's see the example first and later I will explain some key things about Enum in Java.

If you look at the code, you will find that we have used EnumMap to store Enum constant, this is the high-performance Map implementation, which can only be used with enum keys in Java. Since Enum can be compared using == operator as well as equals() method, it gives a choice to use former for better performance. Every Enum in Java implicitly implements java.lang.Enum (compiler does that for you), which provides some convenient methods like the name(), values() and valueOf(), here we have used values() and a for each loop to iterate over all Enum constant, quite a nifty idiom post-Java 5.

That's all on this Simple Java Enum Example. It's enough to get you started with Enum and also demonstrate some of the key features of Java enum. I suggest looking my another article 10 Java Enum Examples and following book JavaDeveloper's Notebook for more information on How to take most of Enum in Java.