Java Reference
In-Depth Information
return result;
}
If you make the call reverse("Mississippi") ,
the method returns
"ippississiM" .
7.3 Reference Semantics
In Java, arrays are objects. We have been using objects since Chapter 3 but we haven't
yet discussed in detail how they are stored. It's about time that we explored the details.
Objects are stored in the computer's memory in a different way than primitive data are
stored. For example, when we declare the integer variable
int x = 8;
the variable stores the actual data. So, we've drawn pictures like the following:
x8
The situation is different for arrays and other objects. With regard to objects, the
variable doesn't store the actual data. Instead, the data are stored in an object and the
variable stores a reference to the location at which the object is stored. So, we have
two different elements in the computer's memory: the variable and the object. Thus,
when we construct an array object such as
int[] list = new int[5];
we end up with the following:
[0]
[1]
[2]
[3]
[4]
list
0
0
0
0
0
As the diagram indicates, two different values are stored in memory: the array
itself, which appears on the right side of the diagram, and a variable called list ,
which stores a reference to the array (represented in this picture as an arrow). We say
that list refers to the array.
It may take some time for you to get used to the two different approaches to stor-
ing data, but these approaches are so common that computer scientists have technical
terms to describe them. The system for the primitive types like int is known as value
semantics, and those types are often referred to as value types. The system for arrays
and other objects is known as reference semantics, and those types are often referred
to as reference types.
 
 
Search WWH ::




Custom Search