Java Reference
In-Depth Information
41
42
// multiply argument by 2
public static void
modifyElement(
int
element)
{
element *=
2
;
System.out.printf(
"Value of element in modifyElement: %d%n"
, element);
}
43
44
45
46
47
48
49
}
// end class PassArray
Effects of passing reference to entire array:
The values of the original array are:
1 2 3 4 5
The values of the modified array are:
2 4 6 8 10
Effects of passing array element value:
array[3] before modifyElement: 8
Value of element in modifyElement: 16
array[3] after modifyElement: 8
Fig. 7.13
|
Passing arrays and individual array elements to methods. (Part 2 of 2.)
Figure 7.13 next demonstrates that when a copy of an individual primitive-type array
element is passed to a method, modifying the
copy
in the called method does
not
affect the
original value of that element in the calling method's array. Lines 26-28 output the value
of
array[3]
before
invoking method
modifyElement
. Remember that the value of this ele-
ment is now 8 after it was modified in the call to
modifyArray
. Line 30 calls method
mod-
ifyElement
and passes
array[3]
as an argument. Remember that
array[3]
is actually one
int
value (8) in
array
. Therefore, the program passes a copy of the value of
array[3]
.
Method
modifyElement
(lines 43-48) multiplies the value received as an argument by 2,
stores the result in its parameter
element
, then outputs the value of
element
(16). Since
method parameters, like local variables, cease to exist when the method in which they're
declared completes execution, the method parameter
element
is destroyed when method
modifyElement
terminates. When the program returns control to
main
, lines 31-32
output the
unmodified
value of
array[3]
(i.e., 8).
The preceding example demonstrated how arrays and primitive-type array elements are
passed as arguments to methods. We now take a closer look at how arguments in general
are passed to methods. Two ways to pass arguments in method calls in many programming
languages are
pass-by-value
and
pass-by-reference
(sometimes called
call-by-value
and
call-by-reference
). When an argument is passed by value, a
copy
of the argument's
value
is
passed to the called method. The called method works exclusively with the copy. Changes
to the called method's copy do
not
affect the original variable's value in the caller.
When an argument is passed by reference, the called method can access the argu-
ment's value in the caller directly and modify that data, if necessary. Pass-by-reference
improves performance by eliminating the need to copy possibly large amounts of data.