Java Reference
In-Depth Information
a0
b a0
0
1
2
3
5
7
-2
7
c a0
Consequently, b and c now refer to the same array. An assignment such as:
b[1]= 6 ;
changes not only b[1] but also c[1] , since b[1] and c[1] are one and the same.
8.1.6
Passing an array as an argument
Consider this procedure:
public void proc( int p1, int [] p2) {
p1= 5;
p2[1]= 6;
}
and a call to it, where b contains the name a0 of an int [] array object:
proc(10, b);
The frame for the call contains parameters p1 and p2 , with values 10 and a0 :
proc: 1
...
p1 10
p2 a0
Notice that b and p2 refer to the same array object.
You already know that the assignment p1= 5; in the body of procedure proc
has no effect outside the method; it changes only parameter p1 , not the corre-
sponding argument. But, since p2 contains a0 , the assignment p2[1]= 6;
changes array a0 and thus has an effect outside the procedure.
Because Java passes arguments “by value”, it is impossible to write a pro-
cedure that is consistent with this specification:
/** Swap x and y */
public static void swap( int x, int y)
However, we can write a procedure that swaps two array elements:
Search WWH ::




Custom Search