o7planning

Java Enums Tutorial with Examples

  1. What is Java Enum
  2. Can use the == operator to compare the elements of enum
  3. Enum in java can be used as an argument on switch statement
  4. Fetch on the element of Enum
  5. Enum can have Constructor and method
  6. Overrides method in enum
  7. Abstract Method in Enum

1. What is Java Enum

Enum in Javais a keyword, a feature which is used to represent fixed number of well known values in Java, For example Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Generics, varargs and static import.
Now we see before enum exists, what java has to do in specific situations:
WeekDayConstants.java
package org.o7planning.tutorial.beforej5;

// This class defines the constants are the days of the week.
public class WeekDayConstants {
  public static final int MONDAY = 2;
  public static final int TUESDAY = 3;
  public static final int WEDNESDAY = 4;
  public static final int THURSDAY = 5;
  public static final int FRIDAY = 6;
  public static final int SATURDAY = 7;
  public static final int SUNDAY = 1;
}
A class with a method returns the job todo in each specific day of week. (Kind of a timetable).
Timetable.java
package org.o7planning.tutorial.beforej5;

public class Timetable {
  // Returns name of Job will do
  public static String getJob(int dayInWeek) {
      if (dayInWeek == WeekDayConstants.SATURDAY
              || dayInWeek == WeekDayConstants.SUNDAY) {
          return "Nothing";
      }
      return "Coding";
  }
}
It is obvious that such code lines are not safe. For example, you call Timetable.getJob(int) function, but the input parameter does not belong to a defined set.
  • No Type-Safety: First of all it’s not type-safe; you can pass any valid int value to dayInWeek
  • No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of day e.g. when you print MONDAY it will print "2" instead of "MONDAY"
See code in Java5:
WeekDay.java
package org.o7planning.tutorial.javaenum;

public enum WeekDay {
   MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
Timetable.java
package org.o7planning.tutorial.javaenum;

public class Timetable {
  public static String getJob(WeekDay weekDay) {
      if (weekDay == WeekDay.SATURDAY || weekDay == WeekDay.SUNDAY) {
          return "Nothing";
      }
      return "Coding";
  }
}

2. Can use the == operator to compare the elements of enum

Enum is a reference object like a class, interface, but it can also use the == operation
Let see how reference objects are compared.
// To compare the reference object, generally used method equals (..)
Object obj1 = .... ;

// Comparing object with null, can use the == operator
if(obj1 == null)  {
 
}

Object obj2 = ....;
// Not null
if (obj1 != null)   {
   // Comparing two objects.
   if(obj1.equals(obj2))   {
       
   }
}
With Enum, you can use the == operator to compare.
CompareEnumDemo.java
package org.o7planning.tutorial.javaenum;

public class CompareEnumDemo {
  public static void main(String[] args) {
      WeekDay today = WeekDay.SUNDAY;
      // Use the == operator to compare two elements of Enum
      if (today == WeekDay.SUNDAY) {
          System.out.println("Today is Sunday");
      }
  }
}

3. Enum in java can be used as an argument on switch statement

Like the primitive data types (int, float, ..) Enum can be used as a parameter in the switch statement.
Let's look at an example:
SwitchDemo.java
package org.o7planning.tutorial.javaenum;

public class SwitchDemo {
   public static void main(String[] args) {
       WeekDay day = WeekDay.THURSDAY;
       switch (day) {
       case MONDAY:
           System.out.println("Working day");
           break;
       case SATURDAY:
       case SUNDAY:
           System.out.println("Holiday");
           break;
       default:
           System.out.println(day);
       }
   }
}

4. Fetch on the element of Enum

We can fetch on all elements of Enum, using the method values (). See examples:
ValuesDemo.java
package org.o7planning.tutorial.javaenum;

public class ValuesDemo {
   public static void main(String[] args) { 
       // Get all the elements of the Enum.
       WeekDay[] allDays = WeekDay.values();
       for (WeekDay day : allDays) {
           System.out.println("Day: " + day);
       }
   }
}
Results of running the example:
Day: MONDAY
Day: TUESDAY
Day: WEDNESDAY
Day: THURSDAY
Day: FRIDAY
Day: SATURDAY
Day: SUNDAY

5. Enum can have Constructor and method

An Enum can have Constructors and methods. Constructors only to initialize the object within the enum, can not call outside. We see an illustration:
Gender.java
package org.o7planning.tutorial.javaenum;

public enum Gender { 
   // Initialize the elements from Constructor.
   // The element is always final, static
   MALE("M", "Male"), FEMALE("F", "Female");
   private String code;
   private String text;

   // Constructor of Enum internal use only
   // Modifier of constructor is private
   // If you do not declare private, java alway understand is private.    
   private Gender(String code, String text) {
       this.code = code;
       this.text = text;
   } 
   // Static method return Gender by code.
   public static Gender getGenderByCode(String code) {
       for (Gender gender : Gender.values()) {
           if (gender.code.equals(code)) {
               return gender;
           }
       }
       return null;
   }
   public String getCode() {
       return code;
   }
   public void setCode(String code) {
       this.code = code;
   } 
   public String getText() {
       return text;
   }
   public void setText(String text) {
       this.text = text;
   }
}
GenderDemo.java
package org.o7planning.tutorial.javaenum;

public class GenderDemo {
  public static void main(String[] args) {
      Gender marryGender = Gender.FEMALE;
      System.out.println("Code: " + marryGender.getCode());
      System.out.println("Text: " + marryGender.getText());

      // Gender[].
      for (Gender gender : Gender.values()) {
          System.out.println(gender.getText());
      } 
      String code ="M";
      Gender gender= Gender.getGenderByCode(code);
      System.out.println("Gender by code: "+ gender);
  }
}
Results of running the example:
Code: F
Text: Female
Male
Female
Gender by code: MALE

6. Overrides method in enum

You can override the method toString () inherited from class Object.
Currency.java
package org.o7planning.tutorial.javaenum;

public enum Currency {
  VND, USD, EURO ;

  @Override
  public String toString() {
      if (this == VND) {
          return "Dong";
      } else if (this == USD) {
          return "Dola";
      }
      return super.toString();
  }
  public static void main(String[] args) {
      Currency money = Currency.USD;
      System.out.println("Money " + money);
      System.out.println("Money " + money.toString());
      System.out.println("VND " + Currency.VND);
      System.out.println("EURO " + Currency.EURO);
  }
}
Results of running the example:
Money Dola
Money Dola
VND Dong
EURO EURO

7. Abstract Method in Enum

Color.java
package org.o7planning.tutorial.javaenum;

public enum Color {
  RED("red") {
      @Override
      public String getHexCode() {
          return "#ff0000";
      }
  },
  GREEN("green") {
      @Override
      public String getHexCode() {
          return "#00ff00";
      }
  },
  BLUE("blue") {
      @Override
      public String getHexCode() {
          return "#0000ff";
      }
  };
  private String name;
  Color(String name) {
      this.name = name;
  }
  public String getName() {
      return name;
  } 
  public abstract String getHexCode();
}

Java Basic

Show More