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:


Best Example of Enum in Java


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


Simple Java Enum Code Example - SoftDrink

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
Simple Java Enum Examples for Beginners 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.


Other Java Enum Tutorials from Java67 Blog

1 comment:

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