Java Reference
In-Depth Information
Before invoking swap
array is {1, 2}
After invoking swap
array is {1, 2}
Before invoking swapFirstTwoInArray
array is {1, 2}
After invoking swapFirstTwoInArray
array is {2, 1}
As shown in Figure 6.7, 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 inde-
pendent of the ones for a[0] and a[1] . The contents of the array are not affected by this call.
Stack
Heap
Stack
Space required for the
swapFirstTwoInArray
method
Space required for the
swap method
int[] array
reference
n2 : 2
n1 : 1
Space required for the
main method
Space required for the
main method
int[] a
reference
int[] a 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 6.7
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 6.7,
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.
6.7 Returning an Array from a 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 }
 
 
 
Search WWH ::




Custom Search