Java Enum: Java Enumeration Tutorial With Examples

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 10, 2024

This tutorial will elaborate on the Java Enum class and constructor. We will learn how to use Enum through various Java programming examples:

This is a special class whose explanation will be provided in detail. An insight into the Java Enum class will be given along with the list of methods that it supports.

Sufficient programs that implement the Java enum concepts and some frequently asked questions that may be asked during the interviews are included in this tutorial for your easy understanding.

=> Check Here To See The Java Training Series For All.

Java Enum

Java Enumeration

A Java enumeration is nothing but a list of instance variables, methods, or constructors. These are a group of constants. The concept of enumeration was introduced in JDK5. The default property of every enumeration constant is public, static, and final.

enum Keyword

Enumeration is created by using a keyword called “enum”.

Given below is the syntax with which we can create an enumeration.

Syntax:

enum enumerated_type_name
{
enumerator1, enumerator2,…enumeratorN;

}

Note: enum can be defined only inside a top-level class or interface or in a static context. It should not be inside a method.

enum Example

In this example, we are going to initialize four enumerators i.e. spade, heart, diamond, and club belonging to an enumerated type called cards.

Then, we will try to print each of these enumerators.

/*
	 * created an enumeration called cards
	 *  with four enumerators.
	 */	
enum cards 
		{
			spade, club, heart, diamond;
		
		}
public class A {	

             public static void main(String[] args) {		
               /*
		 *  stored each of the enumerators in the
		 *  reference variables a1,a2,a3,a4 respectively.
		 *  note that the new keyword was not used here
		 */
		
		cards a1 = cards.spade;
		cards a2 = cards.club;
		cards a3 = cards.heart;
		cards a4 = cards.diamond;
		
		System.out.println("Enumerators are: "+ a1 + "," + a2 + "," +
 a3 + "," + a4);
	}
}

Output:

enum keyword example

Enum Class

One thing you must have noticed in the above example (see comments) is that we did not use a “new keyword” while instantiating. Although the enumerations define a class Enum and the constructors as well, they do not use a new keyword.

We can use the enumerators defined in the same way as the primitive. Enum is a generic class and all the enumerations inherit Enum.

Syntax:

// E is the enumeration type.

class Enum<E extends Enum<E>>

How To Use Enum In Java

Let us see how to use Enum in various scenarios with the help of Java examples:

Inside A Class

Enum can be declared inside or outside (enum keyword example) a class but not inside a method. Here, we will demonstrate how enum is declared inside a class.

In the below example, we have created an enumeration inside a class and then we have fetched the value or enumerator with the help of a reference variable a1.

public class A {	

       /*
	 * created an enumeration called cards
	 * with four enumerators.
	 */

enum cards 
		   {
			spade, club, heart, diamond;
		
		   }	
	
          public static void main(String[] args) {		
        
               /*
		 *  stored each of the enumerators in the
		 *  reference variables a1.
		 *  note that the new keyword was not used here
		 */
		
		cards a1 = cards.heart;
		
		System.out.println("Card is: "+ a1);
	}
}

Output:

Enum inside a class - output

Iterating Enum Through Loops

Here, we will discuss how we can loop through an enum. We have declared enumeration with four enumerators (outside a class). Then we have initialized a for each loop (inside a class) and tried to fetch the value of the enumerators.

/*
	 * created an enumeration called games
	 * with four enumerators.
	 */	

enum games 
		{
			ludo, Chess, Badminton, Cricket;
		
		}

public class A {	

             public static void main(String[] args) {		
       
               /*
		 *  used forEach loop and stored the value in "index"
                *  and printed the value of each enumerator
		 */	
		
		System.out.println("Using for each loop");
		for (games index:games.values()) {
			     System.out.println(index);
		}
		
	}
}

Output:

Iterating through loops

In if-else

In the below program, we have created an enumeration with three different enumerators and then stored the enumerator in the reference variable for one of the specified enumerators.

Then we have started the if condition check where we have implemented two conditions specified with OR so that if one of those conditions is met then it will print the statement specified in the if condition.

Otherwise, it will print the statement specified in the else condition.

/*
	 * created an enumeration called players
	 * with three enumerators.
	 */

enum players 
		{
			sachin, virat, dhoni;
		
		}

public class A {

	public static void main(String[] args) {

		/*
		 * stored enumerator in reference variable a1 for 
		 * contant dhoni 
		 */
		players a1 = players.dhoni;
		
		/*
		 *  Started if statement with OR condition.
		 *  If any of these conditions are met then it will
		 *  print the statement specified inside if statement
		 */
		
		if(a1 == players.virat || a1 == players.sachin) {
			System.out.println("Sachin and Virat are greatest batsmen");
		}
		
		/*
		 * if none of the above condition is met then it will
		 * print the below specified statement
		 */
		
		else {
			System.out.println("Dhoni is the best Captain");
		}
	}
}

Output:

 if-else output

In Switch Statement

In the below program, we have created an enumeration with four enumerators. Then, we stored one of the enumerators in the reference variable. Thereafter, we initialized a Switch statement and checked each of these enumerators.

Upon the occurrence of that particular enumerator, it will print the statement specified in the particular case.

	/*
	 * created an enumeration called players
	 * with four enumerators.
	 */

enum players 
		{
			sachin, dravid, virat, dhoni;
		
		}

public class A {

	public static void main(String[] args) {

		/*
		 * stored enumerator in reference variable a1 for 
		 * contant dravid 
		 */
		players a1 = players.dravid;
		
		
		/*
		 *  Started Switch Statement and if the element
		 *  matches with a1 then it will print the statement
		 *  specified in the case 
		 */
		
		switch(a1) {
		
		// does not match
		case sachin:
			System.out.println("Sachin is best bastman ever");
			break;
		
		// matches
		case dravid:
			System.out.println("Dravid is the best Test Batsman");
			break;
		
		// does not match
		case virat:
			System.out.println("Virat is modern great");
			break;
		
		// does not match
		case dhoni:
			System.out.println("Dhoni is the best captain ever");
			break;
		
		}

	}
}

Output:

Enumeration in switch-statement

Enum Field And Methods

Enum Field

This section will explain the enum field in detail. We can add fields to the Java enum and each enumerator gets these fields. The field value should be assigned to the constructor of the enum.

In the below syntax, we can see that an enumeration has been defined with three enumerators. Beside each enumerator, we have defined a field of type int. (E.g. – (3), (2) and (1) respectively).

This sums that Java enum has a constructor that takes an int. This constructor sets the int field. When an enumerator is defined, then that int value (specified for that enumerator) is passed to the constructor.

Syntax:

public enum A {	
	
		/*
		 *  calls a contructor with value
		 *  defined on the respective enumerator
		 */
	
		Enumerator1(3), 
		Enumerator2(2),
		Enumerator3(1)
		
		/*
		 *  semicolon needed for the last enumerator
		 *  if there is a method following it.
		 */
		; 

	private final int constant;

	private A(int constant) {
		this.constant = constant;
	}

}

Note: For example on the Enum field, please refer to the section “Enum Constructor”.

Enum Methods

#1) name()

public final String name() – Returns the name of the invoking constant (unchanged or unaltered).

#2) equals()

public final boolean equals(Object other) – Returns true if obj and the invoking object refer to the same constant.

#3) toString

public String toString() – Returns the name of the invoking constant. Not necessarily matches the name used in the enumeration’s declaration.

#4) clone

protected final Object clone()
throws CloneNotSupportedException – This means that the enum will throw an exception when tried to clone.

#5) hashCode()

public final int hashCode() – Returns the hash code for the invoking object.

#6) finalize()

protected final void finalize() – enum class can’t have finalized methods. No return value.

#7) compareTo()

public final int compareTo(E obj) – This compares the enum with the specified object obj. It returns negative if the object is less than the specified object. It returns positive if this object is greater than the specified object obj and it returns zero if the specified obj is equal to this object.

#8) getDeclaringClass

public final Class<E> getDeclaringClass() – Returns the enumeration type (also known as enum declaring class) of which the invoking constant is a member.

#9) ordinal(), values() and valueOf()

All these methods are a part of the package java.lang.Enum. The ordinal () method returns the order of the enumeration constant based on the index of the constant.

The values() method returns all the values present in the enumeration. The valueOf(String) method returns the enumeration constant of the input String. If the String specified is not matched with the constant then it will throw IllegalArgumentException.

Given below is the programming example where we have used the same example (as enum keyword example) and implemented the concept of all the three methods.

/*
	 * created an enumeration called cards
	 * with four enumerators.
	 */	

enum cards 
		{
			spade, club, heart, diamond;
		
		}

public class A {	

          public static void main(String[] args) {		

               /*
		 * created an array arr[] which will store the
		 * value of the constants/enumerators declared in the enumeration 
		 */
		
		 cards arr[] = cards.values();
               /*
		 *  used forEach loop and stored the value in "type"
		 *  and printed the value as well as index with the help of 
		 *  ordinal() method
		 */
		
		for (cards type:arr) {
			   System.out.println(type + " occurs at " + type.ordinal());
		}
		
		/*
		 *  passed heart as an input String which matches with the
		 *  constant declared in "cards"
		 */
		
		System.out.println(cards.valueOf("heart"));
	}
}

Output:

ordinal(), values() and valueOf()

Enum Constructor

Enum (as it is also a class) does support constructor to pass data during the creation of enumerators or also known as enum constants.

The main property of an enum constructor is that they are private or private-package. This means that either they are accessible within a class or within a package.

Let’s see the below example. Here we have made use of both i.e. method and the constructor. First of all, we have created an enumeration named “players” that has five enumerators and the field.

Then, we have a constructor and a method that will return the number of runs scored by each player or enumerator or enum constant.

Thereafter, we have the main class in which we have made use of for each loop with the values() method to store and iterate each enumerator. Also, we have called the method for the number of runs scored by each player.

/*
	 * Created enumeration players with the field.
	 * Declared a constructor and a method to return
	 * the number of runs scored by the players.
	 */
	
	enum players {
		dravid(10889), 
		sachin(18426), 
		ganguly(11363), 
		virat(11867), 
		dhoni(10773)
		;
		
		private int runs;
	/*
	 * Created enumeration players with the field.
	 * Declared a constructor and a method to return
	 * the number of runs scored by the players.
	 */
	
	enum players {
		dravid(10889), 
		sachin(18426), 
		ganguly(11363), 
		virat(11867), 
		dhoni(10773)
		;
		
		private int runs;		
                players(int r) {
		runs = r;
	}	

                int getRuns() {
		return runs;
	}
}
	
	/*
	 * Used values() method to get the enumerators and a for each loop
	 * to get the number of runs scored by each player 
	 */
	
	 public class A {
		   public static void main(String args[]) {

		   for (players a : players.values())
			       System.out.println(a + " has scored " + a.getRuns() + "
 ODI runs");
		   }
		
}

Output:

Constructor Output

Frequently Asked Questions

Q #1) What is the difference between Iterator and Enumeration in Java?

Answer: Given below is the difference between Iterator and Enumeration.

IteratorEnumeration
It is a generic cursor which is used to iterate elements and it is applicable to all the collection class.It is not a generic cursor because it is only applicable to legacy classes such as Enum. Only read permission for a collection class.
Some of the methods are hasNext(), next() for iteration.Some of the methods are hasMoreElements(), nextElement() for iteration.
We can remove the element in a collection using iterator.We cannot remove the element in a collection using Enumeration because it has only read permission.

Q #2) How Enum supports Inheritance?

Answer: Afterall Enum is also a class in Java, so it has to support Inheritance which is a basic principle of OOPS. All enumerations extend java.lang.Enum class. As a class can only extend a single parent, Enum class does not extend any other.

The toString() which is a part of the Enum class (explained in section Enum Method) is overridden in the java.lang.Enum class.

Conclusion

In this tutorial, we have discussed the enumerations, enumerators, Java Enum class and the enum keyword with appropriate examples and explanations wherever required. Also, we have given an insight into the important methods associated with the Enum class with enum field.

An insight into the constructor, enum with if-else, switch, and loops have been provided.

=> Visit Here To Learn Java From Scratch.

Was this helpful?

Thanks for your feedback!

Leave a Comment