System.out.println();
}
public static void main(String args[])
{
// Notice how an array must be created to
// hold the arguments.
int n1[] = { 10 };
int n2[] = { 1, 2, 3 };
int n3[] = { };
vaTest(n1); // 1 arg
vaTest(n2); // 3 args
vaTest(n3); // no args
}
}
The output from the program is shown here:
Number of args: 1 Contents: 10
Number of args: 3 Contents: 1 2 3
Number of args: 0 Contents:
In the program, the method vaTest( ) is passed its arguments through the array v. This
old-style approach to variable-length arguments does enable vaTest( ) to take an arbitrary
number of arguments. However, it requires that these arguments be manually packaged
into an array prior to calling vaTest( ). Not only is it tedious to construct an array each time
vaTest( ) is called, it is potentially error-prone. The varargs feature offers a simpler, better
option.
A variable-length argument is specified by three periods (...). For example, here is how
vaTest( ) is written using a vararg:
static void vaTest(int ... v) {
This syntax tells the compiler that vaTest( ) can be called with zero or more arguments. As a
result, v is implicitly declared as an array of type int[ ]. Thus, inside vaTest( ), v is accessed
using the normal array syntax. Here is the preceding program rewritten using a vararg:
// Demonstrate variable-length arguments.
class VarArgs {
// vaTest() now uses a vararg.
static void vaTest(int ... v) {
System.out.print("Number of args: " + v.length +
" Contents: ");
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home