Core Java

Java Enum

Introduction:

Java Enum is a Java type which is used to define a fixed set of constants.  For instance, if we wish to store the names of all the months like JANUARY, FEBRUARY, MARCH etc we should prefer creating an enum to hold it.

In this tutorial, we’ll learn why using Enums is a good choice. We’ll also learn ways to define and use an Enum type.

Why use Enum Types?

We might argue that why do we need enum to store constants? Afterall, we can create a class which can hold all our named constants:

public class Month {
    private static final int JANUARY = 0;
    private static final int FEBRUARY = 1;
    ...
    private static final int DECEMBER = 11;
}

The issues with the above approach involve:

  1. Type-safety: The constants defined here are not type-safe in the sense that any int value can be used in the places where we expect the user to use one of these defined constants:
    MonthlyReport report = new MonthlyReport();
    report.setMonth(Month.JANUARY);
    report.setMonth(46); // not type-safe, will accept any integer value
    
  2. Printing Constants: When we print one of these defined constants, only its value(0) will be printed and not its name(‘JANUARY’).
  3. Traversal: This approach doesn’t provide any means to traverse through all defined constants.

Enum type in Java is a great way of dealing with constants and supports features like type-safety, easy traversal through all defined constants etc.

Java Enum Definition:

Defining an enum is fairly simple. An enum storing all months would look like:

public enum Month {
    JANUARY,
    FEBRUARY,
    MARCH,
    ...
    DECEMBER
}

To refer to a particular constant, we’ll use:

Month january = Month.JANUARY;

Notice that the type of variable ‘january’ here is Month and not int. So the setMonth() method of MonthlyReport class can be defined to accept a parameter of type Month, thereby providing type-safety.

Internal Implementation:

Java Enum was first introduced in Java v5. The compiler internally creates a static final class for our defined enum type which extends java.lang.Enum class by default.

All the constants defined in an Enum are final and static by default.

By default, all defined constants in an enum are assigned initial values starting from 0, 1, 2 and so on. However, it is also possible to assign custom values to these constants using fields and constructors.

Since enum internally is a Java class, we can define fields, constructors as well as methods in an enum. But it’s important to remember that constructors in our enum type are always private. If we don’t declare it private explicitly,  the compiler will still mark it private.

Enum Usage:

There are many scenarios where we can use enum type to our advantage.

  1. switch Statement: switch statement supports the use of enum type:
    Month month = report.getMonth();
    ...
    switch(month) {
        case JANUARY: System.out.println('January'); 
                        break;
        case FEBRUARY: System.out.println('February'); 
                        break;
        ...
    
    }
  2. Comparing two enum constants: Since each enum constant has a value, it is possible to compare these constants. We can use either equals() method or == for comparison.
    Month month = report.getMonth();
    if(month.equals(Month.JANUARY)) { //works fine
        ...
    }
    if(month == Month.JANUARY) { //works fine
        ...
    }
  3. Iterating through defined constants: Enum type allows us to iterate through all the defined constants using values() method:
    for(Month month: Month.values()) {
        System.out.println(month);
    }

    The above code will print the names of all the constants defined in our enum Month:

    JANUARY
    FEBRUARY
    ...
    DECEMBER

Enum Fields, Constructors, and Methods:

Let’s suppose along with the name of the month, we also wish to store the monthly target of reports to be generated each month. We can achieve that elegantly using enums:

public enum Month{
    JANUARY(250),//250 is the monthly target for January
    ...
    DECEMBER(150);

    private final int minNoOfReports;
    private Month(int minNoOfReports){
        this.minNoOfReports = minNoOfReports;
    }
    int getMinNoOfReports(){
       return minNoOfReports;
    }
}

We can easily invoke the defined methods using an enum constant reference:

int minReportsForJan = Month.JANUARY.getMinNoOfReports(); //250

Note that the definition of enum constants should always come first.

Additionally, the list of enum constants must be terminated by a semicolon(;) when having fields, methods or constructors defined.

Conclusion:

In this quick tutorial, we have learned about Java Enums. We looked at what they are, why and how to use them. We also had a glance at the internal implementation of enums and we now know that they are nothing but a Java class extending from java.lang.Enum.

Be the First to comment.

Leave a Comment

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