2.11. Variables with a Fixed Set of Integer Values

You will often need variables that can have values only from a predefined fixed set. For example, suppose you want to define an integer variable with the name weekday, which will store an integer value representing a day of the week. The variable ideally needs to be limited to seven possible values, one for each of Monday through Sunday. This is a situation where a facility called an enumeration is a natural choice. You could define an enumeration for this situation with the following declaration statement:

enum Day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

This defines a new type, Day, for variables that can store only one or other of the values specified between the braces. The names Monday, Tuesday, and so on through to Sunday are called enumeration constants, and they identify the only values that are allowed for variables of type Day. In fact, these names will correspond to integer values, starting from 0 in this case, but they are not the same as integer variables because they exist only within the context of the enumeration, Day. Note the absence of a semicolon at the end of the definition of the Day enumeration. Because you are defining a type here, no semicolon is required after the closing brace. I used a capital D at the beginning of the type name, Day, because by convention, types that you define begin with a capital letter. The names for the enumeration constants would usually be written beginning ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.