Java Enum Examples with Benefits and Class usage

Enum was introduced in Java 1.5 as a new type whose fields consists of fixed set of constants. For example, in Java we can create Direction as enum with fixed fields as EAST, WEST, NORTH, SOUTH.

In this tutorial, we will learn know how to create an enum, what are the benefits of using enum and features of enum types. We will also learn using Enum valueOf, enum values, EnumSet and EnumMap with examples.

enum is the keyword to create an enum type and similar to class. Let’s see the example of a simple enum type.

package com.journaldev.enums;

public enum ThreadStates {

In above example, ThreadStates is the enum with fixed constants fields START, RUNNING, WAITING and DEAD.

Now let’s see how enum is better than normal constants fields in java classes.

Let’s create a similar constants class in java.

package com.journaldev.enums;

public class ThreadStatesConstant {
	public static final int START = 1;
	public static final int WAITING = 2;
	public static final int RUNNING = 3;
	public static final int DEAD = 4;

Now let’s see both enum and constants in usage:

	 * This method shows the benefit of using Enum over Constants
	private static void benefitsOfEnumOverConstants() {
		//Enum values are fixed
		//we can pass any int constant

	private static void simpleEnumExample(ThreadStates th) {
		if(th == ThreadStates.START) System.out.println("Thread started");
		else if (th == ThreadStates.WAITING) System.out.println("Thread is waiting");
		else if (th == ThreadStates.RUNNING) System.out.println("Thread is running");
		else System.out.println("Thread is dead");
	private static void simpleConstantsExample(int i) {
		if(i == ThreadStatesConstant.START) System.out.println("Thread started");
		else if (i == ThreadStatesConstant.WAITING) System.out.println("Thread is waiting");
		else if (i == ThreadStatesConstant.RUNNING) System.out.println("Thread is running");
		else System.out.println("Thread is dead");

If we look at the above example, we have two risks with using constants that are solved by enum.

  • We can pass any int constant to the simpleConstantsExample method but we can pass only fixed values to simpleEnumExample, so it provides type safety.
  • We can change the int constants value in ThreadStatesConstant class but the above program will not throw any exception and program might not work as expected but if we change the enum constants, we will get compile time exception which removes any possibility of runtime issues.

Output of the above code snippet is:

Thread started
Thread is waiting
Thread is running
Thread is dead
Thread is dead
Thread started
Thread is waiting
Thread is running
Thread is dead
Thread is dead

Now let’s see more features of enum with an example:

package com.journaldev.enums;


 * This Enum example shows all the things we can do with Enum types
 * @author pankaj
public enum ThreadStatesEnum implements Closeable{
		public String toString(){
			return "START implementation. Priority="+getPriority();

		public String getDetail() {
			return "START";
		public String getDetail() {
			return "RUNNING";
		public String getDetail() {
			return "WAITING";
		public String getDetail() {
			return "DEAD";
	private int priority;
	public abstract String getDetail();
	//Enum constructors should always be private.
	private ThreadStatesEnum(int i){
		priority = i;
	//Enum can have methods
	public int getPriority(){
		return this.priority;
	public void setPriority(int p){
		this.priority = p;
	//Enum can override functions
	public String toString(){
		return "Default ThreadStatesConstructors implementation. Priority="+getPriority();

	public void close() throws IOException {
		System.out.println("Close of Enum");

Java Enum Important Points

  • All java enum implicitly extends java.lang.Enum class that extends Object class and implements Serializable and Comparable interfaces, so we can’t extend any class in enum.
  • Since enum is a keyword, we can’t end package name with it, for example com.journaldev.enum is not a valid package name.
  • Java enum can implement interfaces. As in above enum example, it’s implementing Closeable interface.
  • Java enum constructors are always private.
  • We can’t create instance of enum using new operator.
  • We can declare abstract methods in java enum, then all the enum fields must implement the abstract method. In above example getDetail() is the abstract method and all the enum fields have implemented it.
  • We can define a method in enum and enum fields can override them too. For example, toString() method is defined in enum and enum field START has overridden it.
  • Java enum fields has namespace, we can use enum field only with class name like ThreadStates.START
  • Enums can be used in switch statement, we will see it in action later on in this tutorial.
  • We can extend existing enum without breaking any existing functionality. For example, we can add a new field NEW in ThreadStates enum without impacting any existing functionality.
  • Since enum fields are constants, java best practice is to write them in block letters and underscore for spaces. For example EAST, WEST, EAST_DIRECTION etc.
  • Enum constants are implicitly static and final
  • Enum constants are final but it’s variable can still be changed. For example, we can use setPriority() method to change the priority of enum constants. We will see it in usage in below example.
  • Since enum constants are final, we can safely compare them using “==” and equals() methods. Both will have the same result

Java Enum Example

Now we know most of the features of enum, let’s see it in usage and then we will learn some more features of enum.

package com.journaldev.enums;

import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Set;

public class JavaEnumExamples {

	public static void main(String[] args) throws IOException {

	private static void usingEnumSet() {
		EnumSet<ThreadStatesEnum> enumSet = EnumSet.allOf(ThreadStatesEnum.class);
		for(ThreadStatesEnum tsenum : enumSet){
			System.out.println("Using EnumSet, priority = "+tsenum.getPriority());

	private static void usingEnumMap() {
		EnumMap<ThreadStates, String> enumMap = new EnumMap<ThreadStates,String>(ThreadStates.class);
		enumMap.put(ThreadStates.START, "Thread is started");
		enumMap.put(ThreadStates.RUNNING, "Thread is running");
		enumMap.put(ThreadStates.WAITING, "Thread is waiting");
		enumMap.put(ThreadStates.DEAD, "Thread is dead");
		Set<ThreadStates> keySet = enumMap.keySet();
		for(ThreadStates key : keySet){
			System.out.println("key="+key.toString()+":: value="+enumMap.get(key));

	private static void usingEnumInSwitch(ThreadStatesEnum th) {
		switch (th){
		case START:
			System.out.println("START thread");
		case WAITING:
			System.out.println("WAITING thread");
		case RUNNING:
			System.out.println("RUNNING thread");
		case DEAD:
			System.out.println("DEAD thread");

	private static void usingEnumValues() {
		ThreadStatesEnum[] thArray = ThreadStatesEnum.values();
		for(ThreadStatesEnum th : thArray){
			System.out.println(th.toString() + "::priority="+th.getPriority());

	private static void usingEnumValueOf() {
		ThreadStatesEnum th = Enum.valueOf(ThreadStatesEnum.class, "START");
		System.out.println("th priority="+th.getPriority());

	private static void usingEnumMethods() throws IOException {
		ThreadStatesEnum thc = ThreadStatesEnum.DEAD;
		System.out.println("priority is:"+thc.getPriority());
		thc = ThreadStatesEnum.DEAD;
		System.out.println("Using overriden method."+thc.toString());
		thc = ThreadStatesEnum.START;
		System.out.println("Using overriden method."+thc.toString());
		System.out.println("Enum Constant variable changed priority value="+thc.getPriority());


Before explaining other important features of enum, let’s see the output of the above program.

priority is:4
Using overriden method.Default ThreadStatesConstructors implementation. Priority=4
Using overriden method.START implementation. Priority=1
Enum Constant variable changed priority value=10
Close of Enum
th priority=10
START implementation. Priority=10::priority=10
Default ThreadStatesConstructors implementation. Priority=2::priority=2
Default ThreadStatesConstructors implementation. Priority=3::priority=3
Default ThreadStatesConstructors implementation. Priority=4::priority=4
START thread
DEAD thread
key=START:: value=Thread is started
key=RUNNING:: value=Thread is running
key=WAITING:: value=Thread is waiting
key=DEAD:: value=Thread is dead
Using EnumSet, priority = 10
Using EnumSet, priority = 2
Using EnumSet, priority = 3
Using EnumSet, priority = 4

Java Enum Features Explained

  • usingEnumMethods() shows how to create an enum object and how we can use it’s methods. It’s also showing use of setPriority(int i) method to change the variable of enum.
  • usingEnumValueOf() shows the usage of java.util.Enum valueOf(enumType, name) through which we can create an enum object from String. It throws IllegalStateException if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type. It also throws NullPointerException if any of the arguments are null.
  • usingEnumValues() method shows the usage of values() method that returns an array containing all of the values of the enum in the order they are declared. Note that this method is automatically generated by java compiler for every enum. You won’t find values() implementation in java.util.Enum class.
  • usingEnumInSwitch() method shows how to use enum constants in switch case.
  • usingEnumMap() method shows use of java.util.EnumMap, which is introduced in Java 1.5 Collections Framework. EnumMap is Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. We can’t use null as key for EnumMap and EnumMap is not synchronized.
  • usingEnumSet() method shows use of java.util.EnumSet, which is Set implementation for use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet is not synchronized and null elements are not allowed. It also provides some useful methods like copyOf(Collection c), of(E first, E… rest) and complementOf(EnumSet s).

That’s all for java enum tutorial, please share it if you have learned anything new about java enum types. :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe to JournalDev Newsletter
Get the FREE access to JournalDev Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Database Hackers Handbook worth $37 FREE Download Now
'Java Video Tutorial Series' at 83% Discount - Coupon Code '10ACHIEVE' Enroll Now
Advertisment ad adsense adlogger