What is Enum in Java

Enum in java is very similar as classes with some restrictions. Enums are generally used to declare a fixed set of constants. For example the directions(EAST, WEST, NORTH and SOUTH) of a compass or days(Sunday, Monday ...) of a week can be represented as enum type.

An enum is defined using enum keyword. Every enum that we define acts as a Type(data type) which is used to refer the constants of that enum within or outside the enum type. An enum type is also referred as enumeration type.

Every enum that we define is also known as enum type, so words enum and enum type are used interchangeably. Java enums are added from java version 1.5.

Enum declaration in Java

An enum type can be declared separately or it can be declared anywhere inside a class/interface but not inside a method. If defined separately, they must be saved with .java extension. The basic syntax of declaring an enum type is :

 enum EnumName
   {
     CONSTANT1, CONSTANT2, CONSTANT3, ... ; 
   }  
     
 Example:

 enum Directions
   {
     EAST, WEST, NORTH, SOUTH;
   }             

Here EnumName is the name of enum type given by the programmer. An enum type may contain any number of constants. Everything that comes within { } after enum name is the enum body. Semicolon at the end of constants is optional if enum type contains only constants. An enum may contains constructors and methods as well, we will discuss this later in this tutorial.

Every enum in java is internally implemented as class and every constant of an enum is an instance of that class. Each enum type that we define, internally extends java's predefined Enum class. Above enum declaration will be converted as a class like below :

 final class Directions extends java.lang.Enum {
   private Directions(){}
   public final static Direction EAST = new Direction();
   public final static Direction WEST = new Direction();
   public final static Direction NORTH = new Direction();
   public final static Direction SOUTH = new Direction();
 }

Since each enum type extends pre-defined Enum class, it can not extend any other enum type or class, since multiple inheritance in java is not supported. We will discuss inheritance(extends keyword) in later tutorial. An enum type can implement interfaces as well.

Also notice that each constant is declared as public static final. Since it's static, it can be accessed using enum name. Since it's final, it can not be changed once created. It can be changed at design time only.

What does java compiler creates after compilation of an enum type ?

It creates a .class file with same name as enum name.

Is it mandatory to give the enum constants in upper-case ?

No, it's not mandatory, you can give in lower case as well but java convention says that enum constants should be declared in upper case letters.

How to access enum constants

An enum constant can be accessed using enum name. The value of an enum type variable can only be a constant from the list of constants defined inside the enum type. The value of enum type constant is same as the text of enum constant.

 EnumName varName = EnumName.ConstantName;
   
 Example:

 Directions  est = Directions.EAST;  
 System.out.println(est); // prints EAST 
 System.out.println(Directions.NORTH); // prints NORTH      

Enum program in Java

 enum Directions {
      EAST, WEST, NORTH, SOUTH;
  } 
   
 class EnumDemo {
    public static void main(String [] args) { 
       Directions d = Directions.EAST;
       System.out.println("Direction = " + d);
    }
 } 

Save this program as EnumDemo.java, compile as javac EnumDemo.java and run as java EnumDemo

Output:

Direction = EAST

When does enum constants are created in memory ?

Enum constants are created in memory when any of the enum constants is first called or referenced in code. In above program enum constants will be created after execution of line Directions d = Directions.EAST;

Enum with switch case in Java

An enum type variable or enum constant can be used in switch statements as well. The case matching with constant given in bracket () of switch statement will be executed. Each case expression must be a constant defined in enum type, if it's not a default case.

 switch(Directions.NORTH) {
    case EAST: // only constants defined under enum Directions can be used
       // statements
    case WEST:
      // statements  
    .
    .   
  }

Enum comparison in Java

An enum type constant or variable can be compared with another enum constant or variable using ==, or != operator. We can also use equals() method to compare two enum constants or variables.

 Directions d = Directions.EAST;
 if(d == Directions.EAST)  // true
 if(d.equals(Directions.NORTH)) // false

Java program of enum uses in switch and if statement

 enum Directions {                           
     EAST, WEST, NORTH, SOUTH                          
  }
 
 class EnumInSwitchAndIf {                           
    public static void main(String [] args) {                   
        Directions d = Directions.NORTH;
        switch(d) { 
           case EAST: 
             System.out.println("Direction = " + Directions.EAST);
             break;
           case WEST: 
             System.out.println("Direction = " + Directions.WEST);
             break;
           case NORTH:
             System.out.println("Direction = " + Directions.NORTH);
             break;   
           case SOUTH:
             System.out.println("Direction = " + Directions.SOUTH);
             break;
          }
        // Use of enum in if statement
        if(d == Directions.NORTH)
           System.out.println("Current direction = "+d);
      }                         
  }   

Output:

Direction = NORTH
Current direction = NORTH	

Variable, Method and Constructor in Enum

An enum type can have methods, constructors and variables as well, but they must be declared after constant declaration. The first line of code in an enum type must be constant declaration. The enum constant declaration must end with semicolon(;) if the enum type contains method, constructor or field.

If the enum type contains constructor, ensure that you have a matching constructor for each constant declaration since it looks for the matching constructor while compilation. The access modifier of constructor for an enum type must be either private or package-private(no modifier). An enum type can have multiple constructors.

Since each constant in an enum type is internally an instance of enum type, so we can call the methods of an enum type by using it's constants. The program below shows the usage of method, constructor and variable inside an enum type.

Enum program with method, constructor and variable

 enum TrafficSignal {
    // Each constant will call single-argument constructor separately.
    RED("wait"), GREEN("go"), ORANGE("go slowly");
 
    private String action;
    // enum method
    public String getAction(){
        return action;
     } 
    // enum constructor - must be private or package-private
    private TrafficSignal(String actionStr){
        action = actionStr;
     }
  }
 
 class EnumExample {                           
    public static void main(String [] args) {  
       String action =  TrafficSignal.GREEN.getAction();                         
       System.out.println("Action = "+ action);
   }                         
 }  

Output:

Action = go	

Can we create the instance of enum by new keyword ?

No, Java doesn't allow us to invoke an enum constructor, which means we can not create the object of enum type using new keyword. Constructors are called automatically by java.

Can we declare main method in an enum type ?

Yes, and we can compile and run that enum type similar as classes.

values(), valueOf() and ordinal() method of enum type

These are some useful methods which you can use with your enum type. The values() and valueOf() method is added by compiler after compilation of your enum type while ordinal() method is available in predefined Enum class. The general form of these methods are :

 public static enum-type[] values()
 public static enum-type valueOf(String str)
 public final int ordinal()
  • The values() method returns an array of enum-type which contains all the constants values of enum in the order they are declared.
  • The valueOf() method returns the enum constant which is equal to the string passed to this method. The string parameter passed to this method is case-sensitive. If the string is not equal to any of the constant, this method throws an exception.
  • The ordinal() method returns the position number of constant. Each constant in an enum type is given a position number which starts from 0 and goes as 1, 2, 3, 4 ...

Enum program to demonstrate the values(), valueOf() and ordinal() method

 enum Color { 
     RED, GREEN, BLUE; 
 } 

 class EnumMethodsDemo { 
   public static void main(String[] args) { 
      // Calling values() method on enum type
      Color arr[] = Color.values(); 
      // Iteration of enum constants with for-each loop 
      for(Color col : arr) { 
         // ordinal() method to find index of a color. 
         System.out.println("Index of "+col+" = "+ col.ordinal()); 
       } 
      // valueOf() method, returns enum constant equals to given string 
      System.out.println(Color.valueOf("RED"));
      // This line will cause exception if uncommented, 
      // as the string doesn't matches with any constant          
      // System.out.println(Color.valueOf("BLACK")); 
    } 
 }    

Output:

Index of RED = 0
Index of GREEN = 1
Index of BLUE = 2
RED	

Java Enum vs Class

Though enums are internally implemented as classes, following table outlines some of the differences between enum and classes.

Enum Class
Enums are generally used to declared a set of pre-defined constants. Classes are design to expose state and behavior of an object.
Constructor of an enum type can be private or package-private only. A class constructor can have any access modifier.
Objects of enum type can not be created. Objects of classes can be created.
First line of code must be constant declaration. Classes doesn't have any such restrictions.
Enum can not extend another enum. Class can extend another class.
Java compiler adds some methods like values(), valueOf() to an enum type after compilation. No such specific methods are added with classes.
Each enum-type internally extends Enum class. Classes doesn't extend any such class.

When we should use emum in java ?

You should use enum types any time you need to represent a fixed set of constants. If you know all possible values(constant) of an entity at compile time(or design time) and you know that these values won't change later, you should use that entity as an enum type. For example you can use enum for declaring Days name, Month name, Planet names etc as these entities will have fixed set of known values.

★★★
  • Refer source code of java.lang.Enum class to get more details of enum.
  • new keyword can not be used with enum type, even within the enum type itself.
  • enum type defined inside a class is implicitly static.
  • equals() and "==" for enum constants evaluates to same result.
  • name() and valueOf() methods returns the text of enum constants. You can override toString() method to return some other content.
  • An enum type can also have abstract method. In this case each constant must implement the abstract method.