Java Reference
In-Depth Information
SELF-REVIEW QUESTIONS (see answers in Appendix N)
SR 8.17 What is a command-line argument?
SR 8.18 Write a main method for a program that outputs the sum of the string
lengths of its first two command-line arguments.
SR 8.19 Write a main method for a program that outputs the sum of the values
of its first two command-line arguments, which are integers.
8.5 Variable Length Parameter Lists
Suppose we wanted to design a method that processed a different amount of data
from one invocation to the next. For example, let's design a method called average
that accepts a few integer values and returns their average. In one invocation of
the method we might pass in three integers to average:
mean1 = average(42, 69, 37);
In another invocation of the same method we might pass in seven integers to
average:
mean2 = average(35, 43, 93, 23, 40, 21, 75);
To accomplish this we could define overloaded versions of the
average method, but that would require that we know the maxi-
mum number of parameters there might be and create a separate
version of the method for each possibility. Alternatively, we could
define the method to accept an array of integers, which could be of
different sizes for each call. But that would require packaging the integers into an
array in the calling method and passing in one parameter.
Java provides a way to define methods that accept variable-length parameter
lists. By using some special syntax in the formal parameter list of the method, we
can define the method to accept any number of parameters. The parameters are
automatically put into an array for easy processing in the method. For example,
the average method could be written as follows:
KEY CONCEPT
A Java method can be defined to
accept a varying number of
parameters.
public double average ( int ... list)
{
double result = 0.0;
if (list.length != 0)
 
Search WWH ::




Custom Search