BIG
DATA

JAVA

ENUMS IN JAVA

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 

Enumeration(Enum) in Java is a data type, which is used to represent a set of predefined constants. A Java enum type is a special kind of Java class. Enum in Java was introduced in JDK 1.5

Enums are lists of constants. Enum constants are implicitly static and final and you can not change their value once created. Because they are constants, the names of an enum type's fields are in uppercase letters.

Defining Enum

When you need a predefined list of values which do not represent some kind of numeric or textual data, you should use an enum. For instance, you would specify a days-of-the-week enum type as:

public enum Day {
    MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY, SUNDAY  
}

The enum keyword signals to the Java compiler that this type definition is an enum. Now you can refer to the constants in the above enum like this:

Day day = Day.FRIDAY;

Here the day variable can take one of the Day enum constants as value (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY). In the above code, day is set to FRIDAY. You should use enum types any time you need to represent a fixed set of constants.

Enums in Control Statements

You will often have to compare a variable pointing to an enum constant against the possible constants in the enum type. Here is an example of using a Java enum in an if and switch statement.

Day day = Day.FRIDAY;    // or assign some Day constant
if( day == Day.MONDAY) {

} else if( day == Day.FRIDAY) {

} else if( day == Day.SUNDAY) {

}

If your enum type contain a lot of constants, then it might be a good idea to use switch.

Day day = Day.FRIDAY;    // or assign some Day constant

switch (day) {
    case MONDAY : ...; 
	break;
    case FRIDAY : ...; 
	break;
    case SUNDAY : ...; 
	break;
}

Enum Iteration

Enum's static values() method can be used to obtain an array of all the possible values of enum. The java compiler internally adds the values() method when it creates an enum. The values() method returns an array containing all the values of the enum. Here is the code showing Enum iteration.

for (Day day : Day.values()) {
    System.out.println(day);
}

This will print all values of Day enum, like below:

MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

Enum Fields, Constructor and methods

A Java enum type can have a constructor that can be used to initialize instance fields. Like a class ,you can also add fields and methods to a Java enum. Lets look at an example:

enum Day {
    MONDAY  ("Today is Monday"),
    TUESDAY ("Today is Tuesday"),
    WEDNESDAY ("Today is Wednesday"),
	THURSDAY ("Today is Thursday"),
	FRIDAY ("Today is Friday"),
	SATURDAY ("Today is Saturday"),
	SUNDAY ("Today is Sunday")
    ; // semicolon is needed when fields or methods to follow

    private final String dayInfo;

    Day(String dayInfo) {
        this.dayInfo = dayInfo;
    }
    
    public String getDayInfo() {
        return this.dayInfo;
    }    
}

public class enumDemo {

	public static void main(String [] args) 
	{
		for (Day day : Day.values()) {
			System.out.println(day);
			System.out.println(day.getDayInfo());
		}
	} 
} 

Output of the above code would be:

MONDAY
Today is Monday
TUESDAY
Today is Tuesday
WEDNESDAY
Today is Wednesday
THURSDAY
Today is Thursday
FRIDAY
Today is Friday
SATURDAY
Today is Saturday
SUNDAY
Today is Sunday

When the line MONDAY ("Today is Monday") is executed it calls the constructor Day(String dayInfo) {} passing "Today is Monday" to it. The passed string value is then assigned to a enum field called dayInfo within the constructor. So that when you call the enum method getDayINfo() it returns the value stored in field dayInfo.

Enum ValueOf

valueOf method of Java Enum is used to retrieve Enum constant declared in Enum Type by passing String. In other words valueOf method is used to convert String to Enum constants.

Day day = Day.valueOf("FRIDAY");
System.out.println(day.getDayInfo());

Output will be:

Today is Friday

valueOf method is case-sensitive and invalid String will result in IllegalArgumentException. The String passed to valueOf method of Java enum must be same as constant name you have given during enum definition.

Benefits of Enums in Java

  • Enum is type-safe, you cannot assign anything else other than predefined Enum constants to an Enum variable. Compiler will throw error for assigning something else.
  • You can use Enum inside Java Switch statement.
  • You can add new constants to enum without breaking existing code.

Some points on Java Enum

  • Enums in Java are type-safe meaning, you can not assign any value other than specified in Enum Constants.
  • An enum cannot extend anything else. They implicitly extend java.lang.Enum
  • Enum constants are implicitly static and final and can not be changed once created and hence you can safely compare them using "==" equality operator.
  • Enum in java can be used as an argument on switch statment
  • An enum can be declared outside or inside a class, but NOT in a method.
  • Enums constants can only be created inside Enums itself.
  • Enum in Java are reference type. Like class you can define constructor, methods and variables inside java Enum.
  • Constructor of Enum in Java can only be private and hence you can not create instance of enums by using new operator Enum constructors can have arguments, and can be overloaded also. enum constructors can NEVER be invoked directly in code. They are always called automatically when an enum is initialized.
  • Like class, Enum in Java can implement the interface and override any method. And Enums implicitly implement both Serializable and Comparable interface.
  • You can define abstract methods inside Enum in Java and can also provide different implementation for different instances of enum in java.
  • The semicolon at the end of an enum declaration is optional. These are legal:
    enum Day { MON, TUE, WED}
    enum Foo { MON, TUE, WED};