Java Reference
In-Depth Information
System.out.print(array[i] + " " );
}
}
You can invoke it by passing an array. For example, the following statement invokes the
printArray method to display 3 , 1 , 2 , 6 , 4 , and 2 .
printArray( new int []{ 3 , 1 , 2 , 6 , 4 , 2 });
Note
The preceding statement creates an array using the following syntax:
new elementType[]{value0, value1, ..., valuek};
There is no explicit reference variable for the array. Such array is called an anonymous
array .
anonymous array
Java uses pass-by-value to pass arguments to a method. There are important differences
between passing the values of variables of primitive data types and passing arrays.
pass-by-value
For an argument of a primitive type, the argument's value is passed.
For an argument of an array type, the value of the argument is a reference to an array;
this reference value is passed to the method. Semantically, it can be best described as
pass-by-sharing , that is, the array in the method is the same as the array being
passed. Thus, if you change the array in the method, you will see the change outside
the method.
pass-by-sharing
Take the following code, for example:
public class Test {
public static void main(String[] args) {
int x = 1 ; // x represents an int value
int [] y = new int [ 10 ]; // y represents an array of int values
m(x, y)
; // Invoke m with arguments x and y
System.out.println( "x is " + x);
System.out.println( "y[0] is " + y[ 0 ]);
}
public static void
m( int number, int [] numbers)
{
number = 1001 ; // Assign a new value to number
numbers[ 0 ] = 5555 ; // Assign a new value to numbers[0]
}
}
x is 1
y[0] is 5555
You may wonder why after m is invoked, x remains 1 , but y[0] become 5555 . This is
because y and numbers , although they are independent variables, reference the same array, as
illustrated in Figure 6.6. When m(x, y) is invoked, the values of x and y are passed to
number and numbers . Since y contains the reference value to the array, numbers now con-
tains the same reference value to the same array.
 
 
Search WWH ::




Custom Search