Java Reference
In-Depth Information
Listing 6.5 gives another program that demonstrates the effect of passing by value. The pro-
gram creates a method for swapping two variables. The
swap
method is invoked by passing
two arguments. Interestingly, the values of the arguments are not changed after the method
is invoked.
L
ISTING
6.5
TestPassByValue.java
1
public class
TestPassByValue {
2
/** Main method */
3
public static void
main(String[] args) {
4
// Declare and initialize variables
5
int
num1 =
1
;
6
int
num2 =
2
;
7
8 System.out.println(
"Before invoking the swap method, num1 is "
+
9 num1 +
" and num2 is "
+ num2);
10
11
// Invoke the swap method to attempt to swap two variables
12
swap(num1, num2);
false swap
13
14 System.out.println(
"After invoking the swap method, num1 is "
+
15 num1 +
" and num2 is "
+ num2);
16 }
17
18
/** Swap two variables */
19
public static void
swap(
int
n1,
int
n2) {
20 System.out.println(
"\tInside the swap method"
);
21 System.out.println(
"\t\tBefore swapping, n1 is "
+ n1
22 +
" and n2 is "
+ n2);
23
24
// Swap n1 with n2
25
int
temp = n1;
26 n1 = n2;
27 n2 = temp;
28
29 System.out.println(
"\t\tAfter swapping, n1 is "
+ n1
30 +
" and n2 is "
+ n2);
31 }
32 }
Before invoking the swap method, num1 is 1 and num2 is 2
Inside the swap method
Before swapping, n1 is 1 and n2 is 2
After swapping, n1 is 2 and n2 is 1
After invoking the swap method, num1 is 1 and num2 is 2
Before the
swap
method is invoked (line 12),
num1
is
1
and
num2
is
2
. After the
swap
method
is invoked,
num1
is still
1
and
num2
is still
2
. Their values have not been swapped. As shown
in Figure 6.4, the values of the arguments
num1
and
num2
are passed to
n1
and
n2
, but
n1
and
n2
have their own memory locations independent of
num1
and
num2
. Therefore, changes in
n1
and
n2
do not affect the contents of
num1
and
num2
.
Another twist is to change the parameter name
n1
in
swap
to
num1
. What effect does this
have? No change occurs, because it makes no difference whether the parameter and the argu-
ment have the same name. The parameter is a variable in the method with its own memory
space. The variable is allocated when the method is invoked, and it disappears when the
method is returned to its caller.
Search WWH ::
Custom Search