// Notice how vaTest() can be called with a
// variable number of arguments.
vaTest(10);
// 1 arg
vaTest(1, 2, 3); // 3 args
vaTest();
// no args
}
}
The output from the program is the same as the original version.
There are two important things to notice about this program. First, as explained, inside
vaTest( ), v is operated on as an array. This is because v is an array. The ... syntax simply tells
the compiler that a variable number of arguments will be used, and that these arguments will
be stored in the array referred to by v. Second, in main( ), vaTest( ) is called with different
numbers of arguments, including no arguments at all. The arguments are automatically put
in an array and passed to v. In the case of no arguments, the length of the array is zero.
A method can have "normal" parameters along with a variable-length parameter. However,
the variable-length parameter must be the last parameter declared by the method. For example,
this method declaration is perfectly acceptable:
int doIt(int a, int b, double c, int ... vals) {
In this case, the first three arguments used in a call to doIt( ) are matched to the first three
parameters. Then, any remaining arguments are assumed to belong to vals.
Remember, the varargs parameter must be last. For example, the following declaration
is incorrect:
int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!
Here, there is an attempt to declare a regular parameter after the varargs parameter, which
is illegal.
There is one more restriction to be aware of: there must be only one varargs parameter.
For example, this declaration is also invalid:
int doIt(int a, int b, double c, int ... vals, double ... morevals) { // Error!
The attempt to declare the second varargs parameter is illegal.
Here is a reworked version of the vaTest( ) method that takes a regular argument and
a variable-length argument:
// Use varargs with standard arguments.
class VarArgs2 {
// Here, msg is a normal parameter and v is a
// varargs parameter.
static void vaTest(String msg, int ... v) {
System.out.print(msg + v.length +
" Contents: ");
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home