Java Reference
In-Depth Information
When
modifyStacks
returns,
names
still points to the
Stack
containing
“Kim”
and
“Edward”
, and
grades
now points to a
Stack
containing 95, 87, and 50. The output of
StackDemo
is
Kim
Edward
95
87
50
Changing the reference
one
does not change the reference
names
. Although it is
impossible for the
modifyStacks
method to alter the
names
reference, it was quite easy for
the method to modify the object that
names
points to.
The concept of call by value also applies to values returned by a method, as we will see
in the next section. As discussed earlier in this chapter, you need to be able to view code
and determine when an object becomes eligible for garbage collection. When does the
object on line 9 of
StackDemo
become eligible for garbage collection? Because the variable
one
is a parameter, it goes out of scope when the
modifyStacks
method returns on line 10.
Because
one
is the only reference pointing to the
Stack
object from line 9, the object is
eligible for garbage collection after line 10.
Passing References vs. Passing Objects
You need to be able to distinguish the difference between a reference and an object.
When passing arguments to a method, it is the reference that gets passed, not the object.
It is impossible to pass an object to a method. In fact, the largest amount of data that can
be copied into a parameter (or returned from a method) is a
long
or a
double
, both of
which are 64 bits.
Return values are also passed by value, meaning a copy of the data is sent to the calling
method. A method can return
void
, one of the eight primitive types, or a reference: there
are no other possibilities. (Of course, the reference can be of any class or interface type,
so the possible values you can return are actually endless, as long as you realize that a
reference is getting returned, never an actual object!)
Let's look at an example using primitive types. Suppose we have the following method
defi nition:
31. public int max(int a, int b) {
32. int response;
33. if( a < b) {
34. response = b;
35. } else {
Search WWH ::
Custom Search