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 :

Important points of enum :

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.