Java Reference
In-Depth Information
public static void main(String[] args) {
// Define three variables of type Day
Day yesterday = Day.Thursday;
Day today = Day.Friday;
Day tomorrow = Day.Saturday;
// Output the values of the Day variables
System.out.println("Today is " + today);
System.out.println("Tomorrow will be " + tomorrow);
System.out.println("Yesterday was " + yesterday);
}
}
This produces the output:
Today is Friday
Tomorrow will be Saturday
Yesterday was Thursday
How It Works
The code itself is essentially what you saw in the previous section. There is the declaration of the enu-
merated type, Day , with definitions of three variables of that type in main() . You then have output state-
ments for the values of the three variables. Note that enum types cannot be local to a method. If you put
the definition for the Day type within main() , the example does not compile. Here the Day type is local to
the class TryEnumeration that contains the main() method. You could put the definition for Day outside
the TryEnumeration class, in which case it is global.
The output is very interesting. It doesn't display the numerical values of the variables of type Day but
their names. This is the default way in which a value of an enumeration type is represented as a string
because the names are more important than the values in most enumeration types. After all, the values
that they have serve only to differentiate one enumeration constant from another.
This is just a small fraction of the capabilities of enumerations. I introduced the concept at this point
because enumeration constants — the values that a variable of an enumeration type may have — are al-
ways integers. You will find out more about how you can use them as you progress through subsequent
chapters, but you have to wait until Chapter 6 for the full story.
BOOLEAN VARIABLES
Variables of type boolean can have only one of two values, true or false . The values true and false are
boolean literals. The boolean type is named after the mathematician, George Boole, who invented Boolean
algebra, and variables of this type are described as boolean variables. You can define a variable of type
boolean called state with the following statement:
boolean state = true;
This statement also initializes the variable state with the value true .
You can also set the value of a boolean variable in an assignment statement. For example, the statement
Search WWH ::




Custom Search