Enumerations
In this lesson, we look at how to restrict a variable to a finite number of distinct values.
We'll cover the following
What is an enumeration?
Some computations can involve a variable whose value can be one of a seemingly endless array of possibilities. In other cases, a variable’s value can have only certain values. For example, a Boolean variable must be true or false. To represent a letter grade A, B, C, D, or F, we could use a char
variable—grade
, for example—but restrict its value to only those five letters. In reality, however, grade
could
contain any character, not just the letters A, B, C, D, and F. To prevent this, instead of declaring grade
as a char
, we can declare it as an enumerated data type, or enumeration. An enumeration itemizes the values that a variable can have.
For instance, the following statement defines LetterGrade
as an enumeration:
public enum LetterGrade {A, B, C, D, F}
LetterGrade
behaves as a class type. The items listed between the braces in the definition of LetterGrade
are the objects that an object of LetterGrade
can reference. For example, the following statement declares grade
to have LetterGrade
as its data type and assigns A
to grade
:
LetterGrade grade = LetterGrade.A;
We qualify each of these enumerated objects with the name of the enumeration, just as we qualify the named constant PI
with the name of its class Math
. Assigning an object other than A
, B
, C
, D
, or F
to grade
will cause a syntax error. Since these objects behave as constants, we name them as we would a constant by using uppercase letters and the rules for identifiers.
When the compiler encounters an enumeration, it creates a class that has several methods. Among them is toString
, which displays the name of its receiving object. Thus, if we write:
System.out.println(LetterGrade.A);
For example, toString
is called implicitly and the letter A is displayed. You can verify this by running the code given below:
Get hands-on with 1400+ tech skills courses.