What is Enumeration in Java? 

Enum, introduced in Java 5, is a special data type that consists of a set of pre-defined named values separated by commas. These named values are also known as elements or enumerators or enum instances. Since the values in the enum type are constant, you should always represent them in UPPERCASE letters.

You can use an Enum type when you need a fixed set of pre-defined constant values that are known at the compile-time itself. Examples can be days of the week, seasons of the year, etc.

 The following characteristics make enum a ‘special’ class:

  • enum constants cannot be overridden 
  • enum doesn’t support the creation of objects
  • enum can’t extend other classes
  • enum can implement interfaces like classes

Syntax:

In Java, to define an Enum type, the ‘enum’ keyword is used rather than ‘class’ or ‘interface’. Mentioned below is the syntax.

         enum Variable_Name { VALUE_1, VALUE_2, VALUE_3, … }

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

Why Do We Need Enumeration?

Java supports two types of Data Types:

  1. User-Defined Datatypes
  2. Inbuilt Data Types- int, float, double, char, etc. 

Sometimes inbuilt data types are not sufficient. Let’s suppose that we have data of different data types required to be stored in a single variable. In such a situation, inbuilt data types won’t fulfill the need. That’s why there is a requirement for user-defined Data Types, and enum in Java is one of them. 

Examples of Enum in Java: 

EnumJava/EnumJava_1

In the example depicted above, TicketCategory is of the enum type with 4 predefined values which are CRITICAL, HIGH, MEDIUM, and LOW.

Constants in Enum can be referred to in the code later using the ‘dot’ notation operator like below.

TicketCategory category = TicketCategory.HIGH;

How To Define Java Enum?

Enum in Java can be defined outside or within the class.

Syntax: enum Name{constants}

With the following example, we will learn how to define an enum in Java.

Code:

package definition;

enum Car{

     MARUTI,HONDA,TESLA;

}

public classExample{

     public static void main(String [] args) {

          Carc1= Car.HONDA;

          System.out.println(c1);

     }

}

Output:

enum_Name

How To Initialize Specific Values To Java Enums With Example 

Enum in Java can have constructors, methods, and fields. The initial value of enum constants starts from 0. But by defining constructors and fields, it is possible to initialize the specific value to the enum constants. The following example explains this:

Code:

class initialize{  

enum meal{   

BREAKFAST(5), LUNCH(10), SNACKS(15), DINNER(20);   

private int value;  

private meal(int value){  

this.value=value;  

}  

}  

public static void main(String args[]){  

for(meal m: meal.values())  

System.out.println(m+" "+m.value);  

}}  

 Output:

initialize

 Enums With Example

1.  Looping Through Enum

The values() method of enum in Java is useful for looping through an enum's constants.

 Code:

enum Temp{

  Cold,

  Medium,

  Hot

}

public class abc {

  public static void main(String[] args) {

       for(Temp myVar: Temp.values()) {

            System.out.println(myVar);

          }

  }}

 Output:

lopping

2. Enums in Control Flow Statements:

You can use Enums in Control Flow Statements available in the Java programming language such as if-else statement, switch statement, and for-loop statement.

 If-Else Statement:

If you are looking to execute very specific lines of code only when the variable pointing to the Enum constant matches any of the pre-defined values of that Enum type, then the “if-else” statement can be used.

Example:

/EnumJava_8

Switch Statement:

If you want to compare a variable referring to an Enum constant against a lot of pre-defined constant values of that Enum type, then the ‘switch’ statement is more efficient than the multiple if-else statements.           

Example:

EnumJava_9.

For Loop Statement:

If you are looking to iterate over the entire set of pre-defined constant values in Enum and execute a piece of code, then the “for-loop” statement can be used.

Example:

EnumJava_10

3. Enum Fields and Methods

  • Fields:

As mentioned earlier, fields can be added to enum in Java. Each constant enum value gets these fields. When defining the constants, the field values must be supplied to the enum’s constructor as given below:

Code:

class fields{  

     public enum{

         HIGH  (3),  

         MEDIUM(2),  

         LOW   (1); 

         private final int levelCode;

         private Level(int levelCode) {

             this.levelCode= levelCode;

         }

     }}  

In this example, there is a constructor that takes an int and sets the int field. On defining, an int value is passed to the enum constructor. enum in Java constructor can’t be public or protected. 

  •  Standard Enum Methods:

As every Enum type implicitly extends java.lang.Enum class, the following static methods are available with it.

1. values(): This method is used to get an array of all predefined constant values in an Enum type.

Example:

EnumJava_2 

2. ordinal(): Each constant value in enum contains an internal reference number that corresponds to the order in which they are declared, starting with 0. By using this method, you can get the internal reference number for each constant value in Enum.

Example:

EnumJava_3                               

3. valueOf(): This method is used to return an enum constant of the specified string value if it exists.

Example:

EnumJava_4. 

4. toString(): This method is used to get a String value for the given enum constant.

Example

EnumJava_5

Please note that the “toString()” method gets called implicitly if you try to print an enum constant. Try the below example as an exercise.

private enum TicketCategory { CRITICAL, HIGH, MEDIUM, LOW }

System.out.println(TicketCategory.CRITICAL);                

Example:                    

EnumJava_6

Example:             

EnumJava_7

Some other methods of enum in Java are:

  • compareTo()- This method compares the constants of enum on the basis of their ordinal values. For example: meal.LUNCH.compareTo(meal.DINNER) returns ordinal(LUNCH)- ordinal(DINNER)
  • name()-This method returns the defined term of an enum constant in the form of a string. The returned value is FINAL. Example: name(LUNCH) returns “LUNCH”

4. Enum in a Switch Statement

Let us try to use enum in a Switch case and understand its functionality:

 Code:

package switched;

enum Day{

     MON,TUE,WED,THUR,FRI,SAT,SUN;

}

public class Days{

     Day day;

     publicStringAbc(Day day) {

          this.day=day;

     }

     public void Dayis() {

          switch(day) {

          case MON:

               System.out.println("Today is Monday");

               break;

          case TUE:

               System.out.println("Today is Tuesday");

               break;

          case WED:

               System.out.println("Today is Wednesday");

               break;

          case THUR:

               System.out.println("Today is Thursday");

               break;

          case FRI:

               System.out.println("Today is Friday");

               break;

          case SAT:

               System.out.println("Today is Saturday");

               break;

          case SUN:

               System.out.println("Today is Sunday");

               break;

          default:

               System.out.println("Invalid");

               break;

          }

     }}

}

Output:

switchstatement

Note: The main objective of an enum is to define Enumerated Data Types, and enum in Java is more potent than C/C++ enum.

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarthEXPLORE COURSE
Full Stack Java Developer Course

5. Enum Inside Class:

Enums can be placed inside a Java class like below.

public class SupportTicket {

private enum TicketCategory { CRITICAL, HIGH, MEDIUM, LOW }

/* Static fields */

    /* Instance variables */

/* Methods */}

Enum Constructors, Member Variables & Methods

Like Java Classes, Enums can contain Constructors, Member Variables, Methods and also implement Interfaces. However, the only difference is that Enum constants are public, static, and final. Besides, you can instantiate it using the ‘new’ keyword or extend any other class explicitly.

Example: EnumJava_11

Abstract Methods in Enum:

You can also have abstract methods inside Enum type. If there’s an abstract method, then each enum constant value should implement it. It is very useful when you want a different implementation of the method for each constant value.

Example:

EnumJava_12 

Interfaces with Enum:

Similar to Abstract methods, Interface can also be implemented with an Enum type.

Example:

EnumJava_13 

EnumSet:

This abstract class is a specialized implementation of the Java Set that can be used with Enum types. As a member of the Java Collections Framework, this is a more efficient, high-quality, type-safe alternative to HashSet implementation.

All the elements in this EnumSet must contain the same enum type only.

Please note that this is not synchronized and doesn’t allow Null elements. If you try to insert a Null element, it will throw a NullPointerException.

Example:

EnumJava_14

EnumMap:

Like EnumSet, this is also a specialized implementation of the Java Map to be used only with an Enum type.

All the keys of the EnumMap must be of the same single enum type. ‘Null’ keys are not allowed. If you try to insert a Null key, it will throw a NullPointerException. However, ‘Null’ values are allowed.

Example: EnumJava_15

Miscellaneous Details:

In Java Enums, the set of pre-defined constant values must always be in the very first line. And then, these are followed by constructors, member variables, and methods.

Practical Example with complete code for your practice this time. 

enum TicketCategory {

   CRITICAL(1), HIGH(2), MEDIUM(3), LOW(4);                                          

   private final int priority;                                                                         

   TicketCategory(int priority) {                                                               

      this.priority = priority;

   }

   int getPriority() {                                                                                 

      return priority;

   }

}

public class SupportTicket {

public static void main(String[] args) {

System.out.println("Category: Priority");

System.out.println("==============");

for (TicketCategory category : TicketCategory.values()) {

System.out.println("%s: %d", category, category.getPriority());

}

}

}

The output of the above code should be:

Category: Priority

==============

CRITICAL: 1

HIGH: 2

MEDIUM: 3

LOW: 4

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Conclusion:

Enum, introduced in Java 5, is a special data type that comprises a set of pre-defined named values separated by commas. These named values are called elements, or enumerators, or enum instances.

Enum type can be used when you need a fixed set of pre-defined constant values that are needed at the compile time of a program. As these are constant values, you should declare them in UPPER CASES.

In this article, you have learned What is Enum, Enum in If and Switch Statements, Enum Iteration, Enum toString, Enum Methods, EnumSet, EnumMap, Enum Miscellaneous, and required working examples for you to play around with.

If you want to perhaps learn beyond Java and master web application development using diverse programming platforms, Simplilearn's Java Certification Training course is something that you will find to be the ideal option for you. This completely online course from Simplilearn allows you to gain a solid understanding of Java with 60 hours of applied learning covering all the essential topics including Hibernate and Spring structures. It also gives you to get work-ready training with hands-on coding experience that features implementation of two web-based projects too.

Do you have any feedback for us on this “enum in Java” article? Feel free to share them with us by leaving them in the comments section at the bottom of this page. Some subject experts review and will get back to you at the earliest. 

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.