Enum is a useful feature of Java and the best way to represent a fixed number of things like the number of the planet in the solar system, the number of state orders can be, or simply a number of days in a week. Java Enum is different than its predecessor in 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 a 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 its 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.
I have written a lot of articles in Enum, exploring its 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 the title and price, and to demonstrate Enum can override methods, I have overridden the toString() method, which returns custom title passed to each SoftDrink.
To demonstrate Enum can have constructor and member variables, I have provided the title and price, and to demonstrate Enum can override methods, I have overridden the 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.
Java Enum Code Example - SoftDrink
Let's see the example first and later I will explain some key things about Enum in Java.
import java.util.EnumMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Java program to show How to use Enum in Java via a Simple Example * * @author Javin Paul */ public class JavaEnumExample { private static final Logger logger = LoggerFactory.getLogger(JavaEnumExample.class); public static void main(String args[]) { // EnumMap is a special high performance map to store Enum constrants Map<SoftDrink, Integer> store = new EnumMap<SoftDrink, Integer>(SoftDrink.class); // Let's initialize store, by storing 10 canes of each drink // Enum provides an implicit values() method, which // can be used to iterate over Enum for(SoftDrink drink : SoftDrink.values()){ store.put(drink, 10); } // let's print what is in EnumStore for(Map.Entry<SoftDrink, Integer> entry: store.entrySet()){ logger.debug(entry.getKey() + " Qty: " + entry.getValue()+ " Price: " + entry.getKey().getPrice()); } } }public enum SoftDrink{ COKE("Coke", 75), PEPSI("Pepsi", 75), SODA("Soda", 90), LIME("Lime", 50); // Java Enum can have member variables private String title; private int price; // in cents // You can declare constructor for Enum in Java private SoftDrink(String title, int price){ this.title = title; this.price = price; } // Enum can have methods in Java public String getTitle(){ return title; } public int getPrice(){ return price; } // Enum can override methods in Java @Override public String toString() { return title; } } Output 2013-07-03 05:39:42,878 0 [main] DEBUG JavaEnumExample - Coke Qty: 10 Price: 75 2013-07-03 05:39:42,878 0 [main] DEBUG JavaEnumExample - Pepsi Qty: 10 Price: 75 2013-07-03 05:39:42,878 0 [main] DEBUG JavaEnumExample - Soda Qty: 10 Price: 90 2013-07-03 05:39:42,878 0 [main] DEBUG JavaEnumExample - Lime Qty: 10 Price: 50
If you look at the code, you will find that we have used EnumMap to store the 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 the == operator as well as the equals() method, it gives a choice to use the former for better performance.
Every Enum in Java implicitly implements java.lang.Enum (the 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.
Every Enum in Java implicitly implements java.lang.Enum (the 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 how to use Enum in Java. You have seen a common 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 the book Java Developer's Notebook for more information on How to take most of Enum in Java.
Related Java Enum Tutorials for further reading :
- Top 15 Java Enum Interview Questions with Answers (see here)
- Difference between RegularEnumSet and JumboEnumSet in Java (read here)
- String to Enum in Java with Example (check here)
- Can we use Enum in Switch Statement in Java (Yes)
- How to loop over Enum constants in Java (example)
- Learn how to use Enum in Java with a Simple Example (check here)
- Java tip to convert Enum to String in Java (see tip)
- How to use the valueOf method of Enum (check here)
- What Every Java Programmer Should know about Enum (click here)
- 10 points about Enum in Java (see here)
- Can Enum have Constructor in Java (learn here)
Thanks for reading this article so far. If you find this article useful then please share it on Facebook, Twitter, and LinkedIn.
Good example. Just to add Enum can be used to represent State e.g. ON and OFF of buttons, and one of the prime example is using Enum to implement thread sates in JDK itself e.g. NEW, RUNNABLE etc.
ReplyDelete