Java Reference
In-Depth Information
Stack
Heap
Space required for
method
m
int[]
numbers:
int
number: 1
reference
Arrays are
stored in a
heap.
An array of
ten
int
values is
stored here
Space required for the
main method
int[] y
:
int x
:1
reference
F
IGURE
6.6
The primitive type value in
x
is passed to
number
, and the reference value in
y
is passed to
numbers
.
Note
Arrays are objects in Java (objects are introduced in Chapter 8). The JVM stores the objects
in an area of memory called the
heap
, which is used for dynamic memory allocation.
heap
Listing 6.3 gives another program that shows the difference between passing a primitive data
type value and an array reference variable to a method.
The program contains two methods for swapping elements in an array. The first method,
named
swap
, fails to swap two
int
arguments. The second method, named
swapFirstTwoInArray
, successfully swaps the first two elements in the array argument.
L
ISTING
6.3
TestPassArray.java
1
public class
TestPassArray {
2
/** Main method */
3
public static void
main(String[] args) {
4
5
6
// Swap elements using the swap method
7 System.out.println(
"Before invoking swap"
);
8 System.out.println(
"array is {"
+ a[
0
] +
", "
+ a[
1
] +
"}"
);
9
10 System.out.println(
"After invoking swap"
);
11 System.out.println(
"array is {"
+ a[
0
] +
", "
+ a[
1
] +
"}"
);
12
13
// Swap elements using the swapFirstTwoInArray method
14 System.out.println(
"Before invoking swapFirstTwoInArray"
);
15 System.out.println(
"array is {"
+ a[
0
] +
", "
+ a[
1
] +
"}"
);
16
17 System.out.println(
"After invoking swapFirstTwoInArray"
);
18 System.out.println(
"array is {"
+ a[
0
] +
", "
+ a[
1
] +
"}"
);
19 }
20
21
int
[] a = {
1
,
2
};
swap(a[
0
], a[
1
]);
false swap
swapFirstTwoInArray(a);
swap array elements
/** Swap two variables */
22
public static void
swap(
int
n1,
int
n2)
{
23
int
temp = n1;
24 n1 = n2;
25 n2 = temp;
26 }
27
28
/** Swap the first two elements in the array */
29
public static void
swapFirstTwoInArray(
int
[] array)
{
30
int
temp = array[
0
];
31 array[
0
] = array[
1
];
32 array[
1
] = temp;
33 }
34 }