Tutorial

Enum in Java

Published on August 3, 2022
author

Pankaj

Enum in Java

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

Java Enum

java enum, enums in java In this tutorial, we will learn know how to create an Enum. We will also look into the benefits of using enums in java and features of enum types. We will also learn using Java Enum valueOf, enum values, EnumSet and EnumMap with examples.

Java Enum Example

Java enum keyword is used to create an enum type. Let’s have a look at the java enum example program.

package com.journaldev.enums;

public enum ThreadStates {
	START,
	RUNNING,
	WAITING,
	DEAD;
}

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

Java Enum vs Constants

Now let’s see how java 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 how both enum and constants are used in a java program:

/**
* This method shows the benefit of using Enum over Constants
*/
private static void benefitsOfEnumOverConstants() {
	//Enum values are fixed
	simpleEnumExample(ThreadStates.START);
	simpleEnumExample(ThreadStates.WAITING);
	simpleEnumExample(ThreadStates.RUNNING);
	simpleEnumExample(ThreadStates.DEAD);
	simpleEnumExample(null);
		
	simpleConstantsExample(1);
	simpleConstantsExample(2);
	simpleConstantsExample(3);
	simpleConstantsExample(4);
	//we can pass any int constant
	simpleConstantsExample(5);
}

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 the enum.

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

Java Enum Methods

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

package com.journaldev.enums;

import java.io.Closeable;
import java.io.IOException;

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

		@Override
		public String getDetail() {
			return "START";
		}
	},
	RUNNING(2){
		@Override
		public String getDetail() {
			return "RUNNING";
		}
	},
	WAITING(3){
		@Override
		public String getDetail() {
			return "WAITING";
		}
	},
	DEAD(4){
		@Override
		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
	@Override
	public String toString(){
		return "Default ThreadStatesConstructors implementation. Priority="+getPriority();
	}

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

Java Enum Important Points

Below are some of the important points for Enums in Java.

  1. 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.
  2. Since enum is a keyword, we can’t end package name with it, for example com.journaldev.enum is not a valid package name.
  3. Enum can implement interfaces. As in above enum example, it’s implementing Closeable interface.
  4. Enum constructors are always private.
  5. We can’t create instance of enum using new operator.
  6. 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.
  7. 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.
  8. Java enum fields has namespace, we can use enum field only with class name like ThreadStates.START
  9. Enums can be used in switch statement, we will see it in action in the later part of this tutorial.
  10. 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.
  11. 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.
  12. Enum constants are implicitly static and final
  13. 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.
  14. Since enum constants are final, we can safely compare them using “==” and equals() methods. Both will have the same result.

Java EnumSet, EnumMap, valueOf()

Now we know most of the features of Enum, let’s have a look at Java Enum example program. Then we will learn some more features of an enum.

package com.journaldev.enums;

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

public class JavaEnumExamples {

	public static void main(String[] args) throws IOException {
				
		usingEnumMethods();
		
		usingEnumValueOf();
		
		usingEnumValues();
		
		usingEnumInSwitch(ThreadStatesEnum.START);
		usingEnumInSwitch(ThreadStatesEnum.DEAD);
		
		usingEnumMap();
		
		usingEnumSet();
		
	}

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

	private static void usingEnumMap() {
		EnumMap<ThreadStatesEnum, String> enumMap = new EnumMap<ThreadStatesEnum,String>(ThreadStatesEnum.class);
		enumMap.put(ThreadStatesEnum.START, "Thread is started");
		enumMap.put(ThreadStatesEnum.RUNNING, "Thread is running");
		enumMap.put(ThreadStatesEnum.WAITING, "Thread is waiting");
		enumMap.put(ThreadStatesEnum.DEAD, "Thread is dead");
		
		Set keySet = enumMap.keySet();
		for(ThreadStatesEnum 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");
			break;
		case WAITING:
			System.out.println("WAITING thread");
			break;
		case RUNNING:
			System.out.println("RUNNING thread");
			break;
		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());
		thc.setPriority(10);
		System.out.println("Enum Constant variable changed priority value="+thc.getPriority());
		thc.close();
	}

}

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

Important Points

  1. The usingEnumMethods() methods shows how to create an enum object and how we can use its methods. It’s also showing use of setPriority(int i) method to change the variable of enum.
  2. usingEnumValueOf() shows the usage of java.util.Enum valueOf(enumType, name) through which we can create an enum object from String. It throws IllegalArgumentException 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.
  3. 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.
  4. The usingEnumInSwitch() method shows how to use enum constants in switch case.
  5. 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.
  6. 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<E> c), of(E first, E... rest) and complementOf(EnumSet<E> s).

You can checkout all the examples from our GitHub Repository.

Reference: Oracle Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 2, 2020

I cant use method of the object enum in enumSet. Exactly, i cant use getPriority() in usingEnumSet().

- Duc

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 17, 2020

    Which is better Enumset or Final Static String and why?

    - Ajit Sase

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 24, 2019

      Very nice organized and explained.

      - Suraj Sanjay Dangat

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 30, 2018

        Based on your output:- for(ThreadStatesEnum key : keySet){ System.out.println(“key=”+key.toString()+“:: value=”+enumMap.get(key)); } It should be key.getDetail()

        - Chintan

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          December 16, 2018

          Hi Pankaj, I tried compiling the last program JavaEnumExamples. But I am getting 2 errors stating cannot convert Object to ThreadStateEnums. I have modified the program to make it work: package com.journaldev.enums; import java.io.IOException; import java.util.EnumMap; import java.util.EnumSet; import java.util.Set; public class JavaEnumExamples { public static void main(String[] args) throws IOException { usingEnumMethods(); usingEnumValueOf(); usingEnumValues(); usingEnumInSwitch(ThreadStatesEnum.START); usingEnumInSwitch(ThreadStatesEnum.DEAD); usingEnumMap(); usingEnumSet(); } public static void usingEnumMethods() throws IOException { ThreadStatesEnum thc = ThreadStatesEnum.RUNNING; System.out.println("Priority is: " +thc.getPriority()); System.out.println(“Overridden toString() method: " +thc.toString()); thc = ThreadStatesEnum.START; thc.setPriority(10); System.out.println(“Changed Priority Variable is: " +thc.getPriority()); System.out.println(“Overridden toString() method: " +thc.toString()); thc.close(); } public static void usingEnumValueOf() { ThreadStatesEnum th = Enum.valueOf(ThreadStatesEnum.class, “START”); System.out.println(“th priority: " +th.getPriority()); } public static void usingEnumValues() { ThreadStatesEnum[] thArray = ThreadStatesEnum.values(); for(ThreadStatesEnum th : thArray) { System.out.println(th.toString() +”::priority=” +th.getPriority()); } } public static void usingEnumInSwitch(ThreadStatesEnum th) { switch(th) { case START: System.out.println(“START thread”); break; case RUNNING: System.out.println(“Running Thread”); break; case WAITING: System.out.println(“Waiting Thread”); break; case DEAD: System.out.println(“Dead Thread”); break; } } public static void usingEnumMap() { EnumMap enumMap = new EnumMap(ThreadStatesEnum.class); enumMap.put(ThreadStatesEnum.START, “START”); enumMap.put(ThreadStatesEnum.RUNNING, “RUNNING”); enumMap.put(ThreadStatesEnum.WAITING, “WAITING”); enumMap.put(ThreadStatesEnum.DEAD, “DEAD”); Set keySet = enumMap.keySet(); for(Object keyT : keySet) { if(keyT instanceof ThreadStatesEnum) { ThreadStatesEnum key = (ThreadStatesEnum)keyT; System.out.println(“key=”+key.toString() +”::value=” +enumMap.get(key)); } } } public static void usingEnumSet() { EnumSet enumSet = EnumSet.allOf(ThreadStatesEnum.class); for(Object tsenumT : enumSet) { if(tsenumT instanceof ThreadStatesEnum) { ThreadStatesEnum tsenum = (ThreadStatesEnum)tsenumT; System.out.println("Using enumSet, priority = " +tsenum.getPriority()); } } } }

          - Jay Vijay Liya

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            October 30, 2018

            What do you mean by “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.” Do you mean modify enum? I got confused by word “extend”. Do you mean to say something like enum “inheritance”?

            - Raj

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              August 21, 2017

              Thank you for the good explanation and examples. Little remark. In the method “usingEnumMap()” instead “ThreadStates” we need use “ThreadStatesEnum”.

              - Mykhailo

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                June 28, 2017

                Very well written

                - Shankar Ram

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  May 24, 2017

                  ‘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.’ Could you please explain this? How will we be adding new Field? Definitely we are not saying to edit the existing class. Right? Then how do we do that?

                  - Chandrika

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    December 27, 2015

                    As it is written in API Enum.valueOf() doesn’t throw IllegalStateException. It throws IllegalArgumentException “if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type” instead

                    - Bektur Toktosunov

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Featured on Community

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more