Enumerations in Java

Overview

Beginning with JDK 5, enumerations were added to the Java language, and they are now an integral and widely used part of Java. In their simplest form, Java enumerations appear similar to enumerations in other languages. However in Java, an enumeration defines a class type. By making enumerations into classes, the capabilities of the enumeration are greatly expanded. For example, in Java, an enumeration can have constructors, methods, and instance variables.

Key Points

  1. An enumeration is created using the enum keyword. For example, here is a simple enumeration that lists various College departments:
    // An enumeration of various Department.
    enum Department {
         IT, Civil, EC, EE, Mechanical
    }
    

    The identifiers IT, Civil, and so on, are called enumeration constants.

  2. Enumeration constants are implicitly declared as public static final member of enumeration. For example IT, Civil and so on are public static final member of Department enumeration. Furthermore, their type is the type of the enumeration in which they are declared, which is Department in this case. Thus, in the language of Java, these constants are called self-typed, in which “self” refers to the enclosing enumeration.
  3. Enumeration can’t have public or protected constructor.
  4. Even though enumerations define a class type, you do not instantiate an enum using new. Instead, you declare and use an enumeration variable in much the same way as you do one of the primitive types. Example:
    Department dep;
    dep = Department.Civil;
    

    Here dep is a variable of enumeration type Department hence the only values that it can be assigned (or can contain) are those defined by the enumeration. For example dep is assigned the value Civil. Notice that the symbol Civil is preceded by Department.

  5. Two enumeration constants can be compared for equality by using the = = relational operator. For example, below statement compares the value in dep with the IT constant:
    if(dep == Department.IT)  //….
    
  6. An enumeration value can also be used to control a switch statement. Of course, all of the case statements must use constants from the same enum as that used by the switch expression. For example, below switch is perfectly valid:
    // Use an enum to control a switch statement.
    switch (dep) {
         case IT:
              // ...
         case Civil:
              // ...
    

    Notice that in the case statements, the names of the enumeration constants are used without being qualified by their enumeration type name. That is, IT, not Department.IT, is used. This is because the type of the enumeration in the switch expression has already implicitly specified the enum type of the case constants. There is no need to qualify the constants in the case statements with their enum type name. In fact, attempting to do so will cause a compilation error.

  7. When an enumeration constant is displayed, such as in a println( ) statement, its name is output. For example, given this statement:
    System.out.println(Department.IT);
    

    Output will display IT.

  8. All enumerations automatically contain two predefined methods: values( ) and valueOf( ). Their general forms are shown here:
    public static enum-type[] values()
    public static enum-type valueOf(String str)
    

    The values( ) method returns an array that contains a list of the enumeration constants. The valueOf( ) method returns the enumeration constant whose value corresponds to the string passed in str. In both cases, enum-type is the type of the enumeration. For example, in the case of the Department enumeration (see 1st point), the return type of Department.valueOf(“Civil”) is Civil.

    The following program demonstrates the values( ) and valueOf( ) methods:

    // Use the built-in enumeration methods.
    // an enumeration of Department.
    enum Department {
         IT, Civil, EC, EE, Mechanical
    }
    
    class EnumDemo {
        public static void main(String args[]) {
                    Department dep;
            	System.out.println("Here are all Department constants:");
            	// use values()
            	for (Department d : Department.values())
                	     System.out.println(d);
                    System.out.println();
            	// use valueOf()
            	dep = Department.valueOf("Mechanical ");
            	System.out.println("dep contains " + dep);
        }
    }
    

    The output from the program is shown here:

    Here are all Department constants:
    IT
    Civil
    EC
    EE
    Mechanical
    
    dep contains Mechanical
    
  9. As enum defines a class gives the Java enumeration extraordinary power. For example, you can give them constructors, add instance variables and methods, and even implement interfaces. It is important to understand that each enumeration constant is an object of its enumeration type. Thus, when you define a constructor for an enum, the constructor is called when each enumeration constant is created. Also, each enumeration constant has its own copy of any instance variables defined by the enumeration.
  10. First, an enumeration can’t inherit another class. Second, an enum cannot be a superclass. This means that an enum can’t be extended. Otherwise, enum acts much like any other class type. The key is to remember that each of the enumeration constants is an object of the class in which it is defined.
  11. Although you can’t inherit a superclass when declaring an enum, all enumerations automatically inherit one: java.lang.Enum. This class defines several methods that are available for use by all enumerations.

Exploring java.lang.Enum

Enum is a generic class that is declared as shown here:

public abstract class Enum<E extends Enum<E>> implements Comparable<E>, Serializable

Here, E stands for the enumeration type. Enum has no public constructors.

Below is a Class diagram of Enum.

Enum Constructor

protected Enum(String name, int ordinal)

Sole constructor. Programmers cannot invoke this constructor. It is for use by code emitted by the compiler in response to enum type declarations.@param name – The name of this enum constant, which is the identifier used to declare it.

@param ordinal – The ordinal of this enumeration constant (its position in the enum declaration, where the initial constant is assigned an ordinal of zero).

Enum defines several methods that are available for use by all enumerations, which are shown below:

protected
final Object clone() throws CloneNotSupportedException
Throws CloneNotSupportedException. This guarantees that enums are never cloned, which is necessary to preserve their “singleton” status.
public
final
int compareTo(E o)
Compares this enum with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.Enum constants are only comparable to other enum constants of the same enum type. The natural order implemented by this method is the order in which the constants are declared.
public
final
boolean equals (Object other)
Returns true if obj and the invoking object refer to the same constant.
protected
final
void finalize()
enum classes cannot have finalize methods. As final prevents overriding of finalize method. This method has empty body in Enum class.
public
final Class<E> getDeclaringClass()
Returns the type of enumeration of which the invoking constant is a member.Two enum constants e1 and e2 are of the same enum type if and only if

e1.getDeclaringClass() == e2.getDeclaringClass().

public
final
int hashCode()
Returns a hash code for this enum constant (invoking object).
public
final String name()
Returns the unaltered name of the invoking constant.
public
final
int ordinal()
Returns a value that indicates an enumeration constant’s position in the list of constants (where the initial constant is assigned an ordinal of zero)
private
void readObject (ObjectInputStream in) throws IOException,
ClassNotFoundException
Prevent default deserialization.
public String toString() Returns the name of the invoking constant. This name may differ from the one used in the enumeration’s declaration.
public
static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

Examples:

  1. Elaborate Enumeration Fundamentals and Demonstrate ordinal(), compareTo(), and equals(). See Department Enum to understand below example.
// See Enum Department
// Basic example to demonstrate Enumeration.
class EnumDemo {
    public static void main(String[] args) {
        // dep can be assign a value from Department enum only.
        Department dep = Department.EE;
        // Output an enum value (will display EE).
        System.out.println("Value of dep: " + dep);
        // dep is assigned a value EC
        dep = Department.EC;
        // compare two enum values
        if (dep == Department.EC) {
            // Condition is true (Enum can be compared by ==)
            System.out.println("dep contains EC");
        }
        // Use an enum to control a switch statement.
        // case statement must have value from Department enum
        // without being qualified by their enumeration type name
        switch (dep) {
            case IT:
                System.out.println("Department is IT.");
                break;
            case Civil:
                System.out.println("Department is Civil.");
                break;
            case EC:
                System.out.println("Department is EC.");
                break;
            case EE:
                System.out.println("Department is IT.");
                break;
            case Mechanical:
                System.out.println("Department is Mechanical.");
                break;
        }

        // Demonstrate ordinal(), compareTo(), and equals().
        // Obtain all ordinal values using ordinal().
        System.out.println("All department with their oridinal values: ");
        for (Department d : Department.values()) {
            System.out.println(d + "  " + d.ordinal());
        }
        // Demonstrate compareTo() and equals()
        // IT comes before Civil hence below compareTo must return nevagive value
        System.out.print("IT compareTo Civil: ");
        System.out.println(Department.IT.compareTo(Department.Civil));
        System.out.print("EC equals IT: ");
        // EC is not equal to IT hence it will return false
        System.out.println(Department.EC.equals(Department.IT));
    }
}

Output of the program:

All department with their oridinal values:
IT  0
Civil  1
EC  2
EE  3
Mechanical  4
IT compareTo Civil: -1
EC equals IT: false
  1. Another Enumeration Example:
// Enum Holding constants of Score
public enum Score {
    // Score with their minimum value to fall in a category.
    // These all constants are using constructor for object creation by passing their values
    EXCELLENT (600), GOOD (400), AVERAGE (200), POOR (0), NOT_QUALIFIED ( -1);

    // instance variables,
    // every constants of Score will hold their own copy of below variable.
    private int minValue;

    // constructor with argument.
    // ex AVERAGE is calling this constructor by passing value 200
    private Score(int minimum) {
        this.minValue = minimum;
    }

    /**
     * @return the minValue
     */
    public int getMinValue() {
        return minValue;
    }
}

// Class ScoreCard
public class ScoreCard {
    // For getting random number
    Random random = new Random();

    public Score getScoreResult() {
        // provide any random number between 0 to 1000
        int randomNumber = random.nextInt(1000);
        // compare minimum value of each Score constants with random number to get score.
        if (randomNumber >= Score.EXCELLENT.getMinValue()) {
            return Score.EXCELLENT;
        } else if (randomNumber >= Score.GOOD.getMinValue()) {
            return Score.GOOD;
        } else if (randomNumber >= Score.AVERAGE.getMinValue()) {
            return Score.AVERAGE;
        } else if (randomNumber >= Score.POOR.getMinValue()) {
            return Score.POOR;
        } else {
            return Score.NOT_QUALIFIED;
        }
    }
}

// Class to display status (final result)
public class DisplayStatus {
    public static void main(String[] args) {
        System.out.print("Final Status: ");
        // Display the status of score
        System.out.println(new ScoreCard().getScoreResult());
    }
}

Output (it might differ as we are using Random number for displaying score):

Final Status: GOOD
Advertisements

About Sanjay Madnani

Software Developer.
This entry was posted in Tutorials and tagged , , , , , , , . Bookmark the permalink.

3 Responses to Enumerations in Java

  1. Smithd150 says:

    I just like the helpful info you supply on your articles. I will bookmark your blog and take a look at once more here regularly. I’m somewhat sure Ill learn a lot of new stuff right right here! Best of luck for the following! adgcddeefaedgbkc

  2. Johnc677 says:

    I have read several good stuff here. Certainly worth bookmarking for revisiting. I surprise how much effort you put to make such a magnificent informative web site. bedeffcdcbkk

  3. Johnd468 says:

    Pretty great post. I just stumbled upon your blog and wished to say that I’ve really enjoyed surfing around your weblog posts. In any case I will be subscribing to your feed and I am hoping you write again soon! bddccbcedbbb

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s