Search⌘ K
AI Features

Enumerations

Explore how Java enumerations define variables that have a limited set of values. Understand how to declare enumerations, assign them, compare enumerated objects, and use built-in methods such as toString, ordinal, compareTo, and valueOf. This lesson helps you grasp enumeration syntax, their use in class definitions, and their role in creating clear, robust code.

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
...