An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.
In Core Java, an enumeration refers to a data type that consists of a fixed set of named values. In Java, enumerations are implemented using the enum
keyword. Enumerations are often used to represent a set of constants or predefined values that have a meaningful relationship.
Here’s a basic example of declaring and using an enumeration in Java:
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class Main {public static void main(String[] args) {
Day today = Day.WEDNESDAY;
System.out.println(“Today is: “ + today);
}
}
In this example, the Day
enumeration represents the days of the week. The variable today
is assigned the value Day.WEDNESDAY
, and the program prints “Today is: WEDNESDAY.”
Enumerations are useful for improving code readability, providing a way to define a set of related constants in a type-safe manner. Each constant in an enumeration is an instance of the enumeration type. Additionally, enumerations can have methods and fields like a regular class, making them more powerful than simple sets of constants.