Java Reference
In-Depth Information
Display 6.7
Method with a Variable Number of Parameters
(part 2 of 2)
1
import
java.util.Scanner;
This is the file
VariableParameterDemo.java
.
2
public class
VariableParameterDemo
3{
4
public static void
main(String[] args)
5
{
6
System.out.println("Enter scores for Tom, Dick, and Harriet:");
7
Scanner keyboard =
new
Scanner(System.in);
8
int
tomsScore = keyboard.nextInt();
9
int
dicksScore = keyboard.nextInt();
10
int
harrietsScore = keyboard.nextInt();
11
int
highestScore = UtilityClass.max(tomsScore, dicksScore, harrietsScore);
12
System.out.println("Highest score = " + highestScore);
13
}
14
}
Sample Dialogue
Enter scores for Tom, Dick, and Harriet:
55 100 99
Highest score = 100
given as arguments and Java automatically creates an array and places the arguments
in the array.
A parameter specification that specifies any number of parameters, such as
int...
arg
, is called a
vararg
specification
. (It would make more sense to call it a “varparam-
eter” specification, but the word “vararg” is too well entrenched, so we will go along
with common usage.) The three dots in a vararg specification are called an
ellipsis
.
Note that the ellipsis is part of the Java syntax and not an abbreviation used in this
topic. You type in the three dots.
You can have only one variable parameter specification, such as
int...
arg
, in a
method definition. However, you may also have any number of ordinary parameters,
in which case the vararg specification must be the last item on the parameter list. This
is illustrated in Display 6.8, which we discuss in the next subsection.
In Chapter 2, you saw one example of a method that accepts a variable number of
arguments, namely the method
System.out.printf
. However, we could not tell you
how to define such methods yourself until we covered the basics about arrays.
vararg
specification
ellipsis