dsa

Java enums

In this tutorial, we will learn about enums in Java. We will learn to create and use enums and enum classes with the help of examples.

Enumerations serve the purpose of representing a group of named constants in a programming language.

Example

enum Size {
   SMALL, MEDIUM, LARGE, EXTRALARGE
}

class Main {
   public static void main(String[] args) {
      System.out.println(Size.SMALL);
      System.out.println(Size.MEDIUM);
   }
}

Output :
SMALL
MEDIUM

Declaration of enum in java :

  • Enum declaration can be done outside a Class or inside a Class but not inside a Method.
  • First line inside enum should be list of constants and then other things like methods, variables and constructor.
  • According to Java naming conventions, it is recommended that we name constant with all capital letters

Important points of enum :

  • Every enum internally implemented by using Class.
  • Every enum constant represents an object of type enum.
  • enum type can be passed as an argument to switch statement.

Java enum Class

In Java, enum types are considered to be a special type of class. Enum class is present in java.lang package. It is the common base class of all Java language enumeration types. For information about enums, refer enum in java.
Example:

enum Size{
   SMALL, MEDIUM, LARGE, EXTRALARGE;

   public String getSize() {

   // this will refer to the object SMALL
      switch(this) {
         case SMALL:
          return "small";

         case MEDIUM:
          return "medium";

         case LARGE:
          return "large";

         case EXTRALARGE:
          return "extra large";

         default:
          return null;
      }
   }

   public static void main(String[] args) {

      // calling the method getSize() using the object SMALL
      System.out.println("The size of the cake is " + Size.SMALL.getSize());
   }
}


Output

The size of the cake is small

Methods of enum Class:

There are some predefined methods in enum classes that are readily available for use.

  • ordinal() method:The ordinal() method returns the position of an enum constant.
  • compareTo() Method The compareTo() method compares the enum constants based on their ordinal value.
  • toString() MethodThe toString() method returns the string representation of the enum constants.
  • name() MethodThe name() method returns the defined name of an enum constant in string form. The returned value from the name() method is final.
  • valueOf() MethodThe valueOf() method takes a string and returns an enum constant having the same string name.
  • valueOf() MethodThe values() method returns an array of enum type containing all the enum constants.