Java’s types are divided into primitive types and reference types. The primitive types are boolean
, byte
, char
, short
, int
, long
, float
and double
. All nonprimitive types are reference types, so classes, which specify the types of objects, are reference types.
A primitive-type variable can store exactly one value of its declared type at a time. For example, an int
variable can store one whole number (such as 7) at a time. When another value is assigned to that variable, its initial value is replaced. Primitive-type instance variables are initialized by default—variables of types byte
, char
, short
, int
, long
, float
and double
are initialized to 0, and variables of type boolean
are initialized to false
. You can specify your own initial value for a primitive-type variable by assigning the variable a value in its declaration, as in
private int numberOfStudents = 10;
Recall that local variables are not initialized by default.
Programs use variables of reference types (normally called references) to store the locations of objects in the computer’s memory. Such a variable is said to refer to an object in the program. Objects that are referenced may each contain many instance variables. Line 14 of Fig. B.6 creates an object of class GradeBook
, and the variable myGradeBook
contains a reference to that GradeBook
object. Reference-type instance variables are initialized by default to the value null—a reserved word that represents a “reference to nothing.” This is why the first call to getCourseName
in line 18 of Fig. B.6 returned null
—the value of courseName
had not been set, so the default initial value null
was returned.
When you use an object of another class, a reference to the object is required to invoke (i.e., call) its methods. In the application of Fig. B.6, the statements in method main
use the variable myGradeBook
to send messages to the GradeBook
object. These messages are calls to methods (like setCourseName
and getCourseName
) that enable the program to interact with the GradeBook
object. For example, the statement in line 23 uses myGradeBook
to send the setCourseName
message to the GradeBook
object. The message includes the argument that setCourseName
requires to perform its task. The GradeBook
object uses this information to set the courseName
instance variable. Primitive-type variables do not refer to objects, so such variables cannot be used to invoke methods.