What are enumerations in Java? How to retrieve values from an enum?

Java 8Object Oriented ProgrammingProgramming

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.

You can define an enumeration using the keyword enum followed by the name of the enumeration as −

enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Just like arrays, the elements/constants in an enumeration are identified using numbers starting from 0 in the above example the days are identified using numbers as shown in the following illustration −

Retrieving values from an enum

You can retrieve all the elements of an enum using the values() method.

Example

 Live Demo

enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumerationExample {
   public static void main(String args[]) {
      Days constants[] = Days.values();
      System.out.println("Value of constants: ");
      for(Days d: constants) {
         System.out.println(d);
      }
   }
}

Output

Value of constants:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
raja
Published on 05-Jul-2019 12:39:37
Advertisements