codescracker


java

Java Varargs (Variable Length Arguments)



« Previous Tutorial Next Tutorial »


Java Varargs

Beginning with JDK 5, Java has included a feature that simplifies the creation of methods that need to take a variable number of arguments. This feature is called as varargs (short for variable-length arguments).

A method that takes a variable number of arguments is called a variable-arity method, or simply a varargs method.

Situations that require a variable number of arguments be passed to a method are not unusual. For example, a method that opens an Internet connection might take a user name, password, filename, protocol, and so on, but supply defaults if some of this information is not provided. In this situation, it would be convenient to pass only the arguments to which the defaults did not apply. Another example is printf() method that is a part of Java's I/O library, it takes a variable number of arguments, which it formats and then outputs.

Prior to JDK 5, variable-length arguments could be handled in two ways, neither of which was particularly pleasing. First, if the maximum number of arguments was small and known, then you could create overloaded versions of the method, one for each way the method could be called. Although this works and is suitable for some cases, it applies to only a narrow class of situations.

In cases where the maximum number of potential arguments was larger, or unknowable, a second approach was used in which, arguments were put into an array, and then the array was passed to the method. This approach is illustrated by the following program :

Java Varargs Example

Here is an example demonstrating varargs in Java:

/* Java Program Example - Java Varargs (Variable-Length) Arguments
 * Use an array to pass a variable number of arguments
 * to a method. This is the old-style approach to variable-length
 * arguments.
 */

class JavaProgram
{
    static void vaTest(int v[])
    {
        System.out.print("Number of arguments = " + v.length + ", Contents = ");
		
        for(int x : v)
        {
            System.out.print(x + "  ");
        }
		
        System.out.println();
    }
    
    public static void main(String args[])
    {
        
        /* notice how an array must be create to 
         * hold the arguments
         */
        
        int n1[] = { 10 };
        int n2[] = { 1, 2, 3 };
        int n3[] = { };
        
        vaTest(n1);     // 1 argument
        vaTest(n2);     // 3 arguments
        vaTest(n3);     // no arguments

    }
}

When the above Java program is compile and executed, it will produce the following output:

java varargs

In the above program, the method vaTest() is passed its argument through the array v. This old-style approach to the variable-length arguments does enable the vaTest() to take an arbitrary number of arguments. However, it requires that these arguments be manually packaged into an array prior to calling the vaTest(). Not only is it tedious to construct an array each time the 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 the vaTest() is written using a vararg:

static void vaTest(int ... v) {

This syntax tells the compiler that the vaTest() can be called with zero or more arguments. As a result, v is implicitly declared as an array of type int[]. Thus, inside the vaTest(), v is accessed using the normal array syntax. Here is the preceding program rewritten using a vararg:

/* Java Program Example - Java Varargs (Variable-Length) Arguments
 * This program demonstrate variable-length arguments
 */

class JavaProgram
{
    /* vaTest() now uses a vararg */
    static void vaTest(int ... v)
    {
        System.out.print("Number of arguments = " + v.length + ", Contents = ");
		
        for(int x : v)
        {
            System.out.print(x + "  ");
        }
		
        System.out.println();
    }
    
    public static void main(String args[])
    {
        
        /* notice how vaTest() can be called with 
         * a variable number of arguments
         */
        
        vaTest(10);          // 1 argument
        vaTest(1, 2, 3);     // 3 arguments
        vaTest();            // no arguments

    }
}

When the above Java program is compile and executed, it will produce the following output (same as previous one):

java variable length arguments

There are two important things to notice about this program. First, as explained, inside the vaTest(), v is operated on as an array. This is because v is an array. The ... syntax 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 the main(), the 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.

Following is a reworked version of the vaTest() method that takes a regular argument and a variable-length argument :

/* Java Program Example - Java Varargs (Variable-Length) Arguments
 * This program uses varargs with standard arguments
 */

class JavaProgram
{
    /* 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();
    }
    
    public static void main(String args[])
    {
        
        vaTest("One vararg : ", 10);
        vaTest("Three varargs : ", 1, 2, 3);
        vaTest("No varargs : ");

    }
}

When the above Java program is compile and executed, it will produce the following output:

varargs

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test