Java Reference
In-Depth Information
NOTE
There are actually nine primitive data types in Java if you count
void
, which represents nothing. It's used in a method to indicate
that it does not return a value.
Class Types
In addition to the primitive data types, a variable can have a class as its type, as in the
following examples:
2
String lastName = “Hopper”;
Color hair;
VolcanoRobot vr;
When a variable has a class as its type, the variable refers to an object of that class or
one of its subclasses.
The last statement in the preceding list—
VolcanoRobot vr;
—creates a variable named
vr
that is reserved for a
VolcanoRobot
object. You'll learn more tomorrow about how to
associate objects with variables.
Referring to a superclass as a variable type is useful when the variable might be one of
several different subclasses. For example, consider a class hierarchy with a
CommandButton
superclass and three subclasses:
RadioButton
,
CheckboxButton
, and
ClickButton
. If you create a
CommandButton
variable called
widget
, it could refer to a
RadioButton
,
CheckboxButton
, or
ClickButton
object.
Declaring a variable of type
Object
means that it can be associated with any kind of
object.
Assigning Values to Variables
After a variable has been declared, a value can be assigned to it with the assignment
operator, which is an equal sign (“=”). The following are examples of assignment state-
ments:
idCode = 8675309;
accountOverdrawn = false;
Constants
Variables are useful when you need to store information that can be changed as a pro-
gram runs.