Java Reference
In-Depth Information
3. If a method has both a variable length formal parameter and other types
of formal parameters, then the variable length formal parameter must be
the last formal parameter of the formal parameter list.
Before giving more examples of methods with a variable length formal parameter list, we
note the following.
One way to process the elements of an array one-by-one, starting at the first element, is
to use an index variable, initialized to
0
, and a loop. For example, to process the elements
of an array,
list
, you can use a
for
loop, such as the following:
for
(
int
index; index < list.length; index++)
//process list[index]
In fact, this chapter uses these types of loops to process the elements of an array. The most
recent version of Java provides a special type of
for
loop to process the elements of an object,
such as an array. The syntax to use this
for
loop to process the elements of an array is:
for
(dataType identifier : arrayName)
statements
where
identifier
is a variable and the data type of
identifier
is the same as the data
type of the array elements. This form of the
for
loop is called a foreach loop.
For example, suppose
list
is an array and each element is of type
double
, and
sum
is a
double
variable. The following code finds the sum of the elements of
list
:
9
sum = 0;
//Line 1
for
(
double
num : list)
//Line 2
sum = sum + num;
//Line 3
The
for
statement in Line 2 is read for each
num
in
list
. The identifier
num
is initialized
to
list[0]
. In the next iteration, the value of
num
is
list[1]
, and so on.
Using the foreach loop, the
for
loop in the method
largest
, in Example 9-10, can be
written as:
for
(
double
num : list)
{
if
(max < num)
max = num;
}
(The modified program, named
LargestNumberVersionII.java
, that uses the foreach
loop to determine the largest element in
list
, can be found with the Additional Student
Files at www.cengagebrain.com.)
Example 9-11 shows that the variable length formal parameters (list) of a method can be
objects. This example uses the
class
Clock
designed in Chapter 8.
Search WWH ::
Custom Search