Varargs: Variable Arguments to Methods

Java 5 introduced a new feature called varargs, which allows methods to accept variable number of arguments. Varargs are specifically useful in cases where we are not sure about the number of arguments that should to be passed to a method.

Method Signature with Varargs:

public void myMethod(int ... arg){
}

Three dots (…) called as ellipsis is used to indicate varargs parameter in Java.


Example

The add method shown below accepts variable parameters. We have called the add method with different number of parameters from the main method. It will add the numbers passed as parameters and print the output. Note that it also accepts zero arguments.

public class Varargs {
    
    public static void main(String[] args) {
        Varargs v = new Varargs();
        v.add(10, 12, 23, 11);
        v.add(1, 5, 12);
        v.add(6,8);
        v.add();
    }
    
    public void add(int ... params){
        int sum=0;
        for(int param: params){
            sum = sum + param;
        }
        System.out.println("Sum :"+ sum);
    }
}
Output:
Sum :56
Sum :18
Sum :14
Sum :0

Life without Varargs

There are two approaches used prior to JDK 5 to handle variable-length arguments:

  1. We could use overloaded versions of the method, each method having different number of arguments. This can be used only when the number of arguments is known and limited. However using varargs saves a lot of coding.
  2. All the arguments can be put into an array and passed to the method. Although this works but we are required to manually package the arguments into the array.

Normal Parameters with Varargs

Java allows using normal parameters with varargs. However there is one restriction, the varargs parameter should be the last parameter declared in the method.

public void myMethod(int normal, int ... arg){
}

Here the first parameter passed to myMethod() will match with the normal parameter, any other parameters will be treated as varargs.


Overloading Varargs Methods

Varargs methods can be overloaded. The example below overloads the add() method we used earlier.

public void add(int ... params){
    int sum=0;
    for(int param: params){
         sum = sum + param;
    }
    System.out.println("Sum :"+ sum);
}

public void add(String message, int... params){
    int sum=0;
    for(int param: params){
	sum = sum + param;
    }
    System.out.println(message + sum);
}
add(10, 13, 45);                  // Sum :68
add(“The sum is:”, 10, 13, 45); // The sum is :68

Ambiguity with Overloading

While overloading varargs methods, ambiguity might arise when we try to call the overloaded methods and the compiler is not able to resolve the call to a particular method.

The example below demonstrates the ambiguity situation. We have shown three overloaded versions of the add() method.

public void add(int ... params){
    int sum=0;
    for(int param: params){
        sum = sum + param;
    }
    System.out.println("Sum :"+ sum);
}

public void add(int a, int... params){ 
    int sum=0;
    sum = sum + a; 
    for(int param: params){
        sum = sum + param;
    }
    System.out.println(“The sum is” + sum);
}

public void add(double... params){ double sum=0; for(double param: params){ sum = sum + param; } System.out.println("Double Sum" + sum); }

The following calls are ambiguous:

add();    // Compiler can’t decide whether to resolve to the 1st method(int type) or the 3rd(double type)
add(10); // Compiler cannot decide whether to resolve to the 1st or 2nd method i.e. where the parameter is a
// normal or a varargs parameter.
RELATED ARTICLES

2 ways to Create a Thread in Java

Threads in Java can be created in 2 different ways, extending the Thread class and implementing the Runnable interface. This article explains the two ways with suitable examples.

View Article

4 Different Ways of Creating an Object in Java

Most of us have created object using new operator in Java. Did you know the other ways to create objects in Java. This article talks about 4 different ways of creating objects in Java.

View Article

Using AutoCloseable with 'try-with-resources'

Java 7 added the java.lang.AutoCloseable interface that developers can implement in their custom classes for using them with try-with-resources.

View Article

Chained Exception

Chained exception is a feature introduced with JDK 1.4, which allow developers to associate an exception with another exception.

View Article

Shallow Cloning and Deep Cloning

Cloning an object can happen in two ways Deep and Shallow Cloning. In shallow cloning only object references are copied while in deep copy actual objects are copied to the newly cloned object.

View Article

Exception Handling in Inheritance

There are certain rules that must be followed while throwing exceptions in inheritance and overriding methods. This article discuss about these rules.

View Article

Garbage Collection in Java

Java Garbage Collector is a boon to Java developers; it allows developers to program without worrying about memory management. This article describes the working of Java Garbage Collector in details.

View Article

Understanding static and final in Java

Java provides various modifiers which when used with variables, methods or classes, provides them with special properties. Static and final are are two such modifiers which are used frequently by Ja..

View Article

Understanding Object Cloning

Java provides the clone() method which can be used to create a copy an object. It creates a new memory location and copies the content of the object being cloned into the new location.

View Article

Try-with-resources Statement in Java 7

Java 7 introduces the new 'try-with-resources' statement which help developers to overcome the tedious task of closing the resources that have been used in the program.

View Article