O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required