Programming and Problem Solving with Java

(やまだぃちぅ) #1
3.1 Overview of Java Data Types | 101

Primitive type Reference type
letter
'J'

title

"Programming and Problem Solving with Java"

01011010101

01011010101

01011010101

Memory address number of the
start of the string value

Location containing
first part of string

Subsequent locations in memory

After executing the assignment: bookName = title;
bookName

Figure 3.2 Primitive types and reference types


letter = 'J';
title = "Programming and Problem Solving with Java";
bookName = title;


When we declare the variablesletter,title, andbookName, addresses are assigned to these vari-
ables. When we assign the value'J'to thecharvariableletter, Java stores the value'J'into it.
When we assign the string"Programming and Problem Solving with Java"to theStringvariable
title, Java chooses locations into which to store the string, and it stores theaddressof the first
location intotitle. If we assign the value oftitleto anotherStringvariable calledbookName,
then Java simply copies the value stored intitle(the address) to the place it chose forbookName.
Figure 3.2 illustrates the difference between primitive and reference types. It also demon-
strates that a reference type offers the advantage of saving memory space when copying val-
ues that take up multiple locations in memory. The lengthy value is stored just once, and each
of the variables assigned that value takes up just one location. If Java stored reference types
the same way it stores primitive types, it would have to store a copy of the whole value in
each variable, which would consume more space.
The fact that only one copy of an object exists is, however, a double-edged sword. If you
assign an integer value to several variables and then change the value in one of those vari-
ables, the change doesn’t affect any of the other copies. With a reference type, in contrast,
each variable stores a reference to the single copy of the object. Thus, if you change the ob-
ject through one of the references, then it affects all of the other references.

Free download pdf