What are enumerations?

Available since Java 2, version 5.0 (2004), Java enumerations provide a long-awaited facility that programmers familiar with other langueages like C/C++ had been requesting. Essentially, a Java enumeration allows the programmer to create a type (the enumeration) whose values are a list of named constants chosen by the programmer. In Java, however, enumerations are somewhat more capable (and therefore more complex) than that.

Example

enum Color { RED, GREEN, BLUE, YELLOW };

Here enum is a Java keyword, Color is the name of the enumerated type, and RED, BLUE, ... are the (only possible) values of that type.


Once such a type has been defined, variables of that type can also be defined in the usual way.

Example

Color myColor;
Color yourColor = Color.RED; //

The fact that we need to use Color.RED to access the value RED suggests that there may be more going on here than meets the eye, which in fact is the case. In fact, this looks like we are accessing a public static member of a class, and that is just what we are doing, because in Java an enumeration is actually a class (which is not at all the case in C or C++, where the enumeration values are nothing more than names for integers).