Java Reference
In-Depth Information
6.14
True or false? When an array is passed to a method, a new array is created and passed
to the method.
Check
Point
6.15
Show the output of the following two programs:
public class Test {
public static void main(String[] args) {
int number = 0 ;
int [] numbers = new int [ 1 ];
public class Test {
public static void main(String[] args) {
int [] list = { 1 , 2 , 3 , 4 , 5 };
reverse(list);
for ( int i = 0 ; i < list.length; i++)
System.out.print(list[i] + " " );
m(number, numbers);
}
System.out.println( "number is " + number
+ " and numbers[0] is " + numbers[ 0 ]);
public static void reverse( int [] list) {
int [] newList = new int [list.length];
}
public static void m( int x, int [] y) {
x = 3 ;
y[ 0 ] = 3 ;
for ( int i = 0 ; i < list.length; i++)
newList[i] = list[list.length - 1 - i];
}
list = newList;
}
}
}
(a)
(b)
6.16
Where are the arrays stored during execution? Show the contents of the stack and
heap during and after executing displayArray , countLetters , displayCounts
in Listing 6.4.
6.9 Variable-Length Argument Lists
A variable number of arguments of the same type can be passed to a method and
treated as an array.
Key
Point
You can pass a variable number of arguments of the same type to a method. The parameter in
the method is declared as follows:
typeName... parameterName
In the method declaration, you specify the type followed by an ellipsis ( ... ). Only one
variable-length parameter may be specified in a method, and this parameter must be the last
parameter. Any regular parameters must precede it.
Java treats a variable-length parameter as an array. You can pass an array or a variable
number of arguments to a variable-length parameter. When invoking a method with a variable
number of arguments, Java creates an array and passes the arguments to it. Listing 6.5 con-
tains a method that prints the maximum value in a list of an unspecified number of values.
L ISTING 6.5 VarArgsDemo.java
1
public class VarArgsDemo {
2
public static void main(String[] args) {
pass variable-length arg list
pass an array arg
3
4
5 }
6
7
printMax( 34 , 3 , 3 , 2 , 56 . 5 );
printMax( new double []{ 1 , 2 , 3 });
a variable-length arg
parameter
public static void printMax(
double ... numbers
) {
8 if (numbers.length == 0 ) {
9 System.out.println( "No argument passed" );
 
 
Search WWH ::




Custom Search