Consider a program that provides directions for a robot. The directions that the robot can use are as follows: NORTH, SOUTH, EAST, and WEST.
- What data type should be used to store these directions?
Did you answer String
? A String
can be used to store the directions of the robot.
Another Way
The options for the directions are finite. There are only 4 directions provided. However, the number of String
values that could be stored is not finite. Creating an enum
allows us to create a new data type that is restricted to a finite list of values.
An enum
is a type of class. It represents a group of named constants. They are used when we know all the possible values, such as in the example of the directions for the robot. Other examples might include:
- list of menu options,
- suits in a deck of cards, or
- the primary colors (red, orange, yellow, green, blue, and purple).
Structure
Use the keyword enum
followed by the name of this grouping of constants. Then in braces, list the values that can be represented. These values are the enum
type's fields and are constant. Because they are all constants, they should be in all uppercase letters.
enum EnumName {
FIRSTVALUE, SECONDVALUE,THIRDVALUE
}
Creating an Object of the Type
To create an object of this type, we need to declare a variable for the object and assign it to a value. The value that we are assigning will be one of the listed constants. To distinguish between the constant and a String, we will need to use the name of the enum
then the dot operator and the constant.
EnumName objName = EnumName.FIRSTVALUE;
Your Turn
Resources
Next Learn Tutorial
Learn: Introduction to Type Conversions with Casting