Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

3.3 Primitive Types vs. Reference Types

Java’s types are divided into primitive types and reference types. In Chapter 2, you worked with variables of type int—one of the primitive types. The other primitive types are boolean, byte, char, short, long, float and double, each of which we discuss in this book—these are summarized in Appendix D. All nonprimitive types are reference types, so classes, which specify the types of objects, are reference types.

A primitive-type variable can hold exactly one value of its declared type at a time. For example, an int variable can store one integer at a time. When another value is assigned to that variable, the new value replaces the previous one—which is lost.

Recall that local variables are not initialized by default. Primitive-type instance variables are initialized by default—instance 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;

Programs use variables of reference types (normally called references) to store the addresses 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 10 of Fig. 3.2:


Scanner input = new Scanner(System.in);

creates an object of class Scanner, then assigns to the variable input a reference to that Scanner object. Line 13 of Fig. 3.2:


Account myAccount = new Account();

creates an object of class Account, then assigns to the variable myAccount a reference to that Account object. Reference-type instance variables, if not explicitly initialized, are initialized by default to the value null—which represents a “reference to nothing.” That’s why the first call to getName in line 16 of Fig. 3.2 returns null—the value of name has not yet been set, so the default initial value null is returned.

To call methods on an object, you need a reference to the object. In Fig. 3.2, the statements in method main use the variable myAccount to call methods getName (lines 16 and 26) and setName (line 21) to interact with the Account object. Primitive-type variables do not refer to objects, so such variables cannot be used to call methods.

  • + Share This
  • 🔖 Save To Your Account