Thursday, July 25, 2013

Variables with a Fixed Set of Integer Values

You will usually would like variables which will have values solely from a predefined fastened set. for instance, suppose you wish to outline associate degree whole number variable with the name weekday, which can store associate degree whole number worth representing each day of the week. The variable ideally must be restricted to seven potential values, one for every of Monday through Sunday. this is often a state of affairs wherever a facility known as associate degree enumeration may be a natural alternative. you'll outline associate degree enumeration in Java for this case with the subsequent declaration statement:

enum Day

This defines a replacement kind, Day, for variables which will store only 1 or alternative of the values such that between the braces. The names Monday, Tuesday, and then on through to Sunday square measure known as enumeration constants, and that they establish the sole values that square measure allowed for variables of kind Day. In fact, these names can correspond to whole number values, ranging from zero during this case, however they're not constant as whole number variables as a result of they exist solely inside the context of the enumeration, Day. Note the absence of a punctuation at the tip of the definition of the Day enumeration. as a result of you're shaping a kind here, no punctuation is needed once the closing brace. I used a capital D at the start of the kind name, Day,because by convention, sorts that you simply outline begin with a capital. The names for the enumeration constants would sometimes be written starting with a minuscule letter, however during this case I used a capital at the start as a result of that’s however the times of the week square measure sometimes written. you'll even as well write the enumeration constants with a minuscule letter.

No comments:

Post a Comment

Thanks for Commenting......