Java Reference
In-Depth Information
As shown in Figure 7.6, the two elements are not swapped using the
swap
method. However,
they are swapped using the
swapFirstTwoInArray
method. Since the parameters in the
swap
method are primitive type, the values of
a[0]
and
a[1]
are passed to
n1
and
n2
inside
the method when invoking
swap(a[0], a[1])
. The memory locations for
n1
and
n2
are
independent of the ones for
a[0]
and
a[1]
. The contents of the array are not affected by
this call.
Stack
Heap
Stack
Activation record for the
swapFirstTwoInArray
method
Activation record for
the
swap
method
int[]
array
reference
n2
:2
n1
:1
Activation record for
the
main
method
Activation record for the
main
method
int[] a
int[] a
reference
reference
a[0]
:1
a[1]
:2
Invoke
swap(int n1, int n2)
.
The primitive type values in
a[0]
and
a[1]
are passed to the
swap
method.
Invoke
swapFirstTwoInArray(int[]
array)
. The reference value in
a
is passed
to the
swapFirstTwoInArray
method.
The arrays are
stored in a
heap.
F
IGURE
7.6
When passing an array to a method, the reference of the array is passed
to the method.
The parameter in the
swapFirstTwoInArray
method is an array. As shown in Figure 7.6,
the reference of the array is passed to the method. Thus the variables
a
(outside the method)
and
array
(inside the method) both refer to the same array in the same memory location.
Therefore, swapping
array[0]
with
array[1]
inside the method
swapFirstTwoInArray
is the same as swapping
a[0]
with
a[1]
outside of the method.
When a method returns an array, the reference of the array is returned.
Key
Point
You can pass arrays when invoking a method. A method may also return an array. For exam-
ple, the following method returns an array that is the reversal of another array.
l
public static int
[] reverse(
int
[] list) {
2
int
[] result =
new int
[list.length];
create array
3
4
for
(
int
i =
0
, j = result.length -
1
;
5 i < list.length; i++, j--) {
6 result[j] = list[i];
7}
8
9
list
return array
return
result;
result
10 }
Line 2 creates a new array
result
. Lines 4-7 copy elements from array
list
to array
result
. Line 9 returns the array. For example, the following statement returns a new array
list2
with elements
6
,
5
,
4
,
3
,
2
,
1
.
int
[] list1 = {
1
,
2
,
3
,
4
,
5
,
6
};
int
[] list2 = reverse(list1);
Search WWH ::
Custom Search