Monday, January 22, 2018

Varargs (Variable-length Arguments) in Java

varargs in Java short for variable-length arguments is a feature that allows the method to accept variable number of arguments (zero or more). With varargs it has become simple to create methods that need to take a variable number of arguments. The feature of variable argument (varargs) has been added in Java 5.


Syntax of varargs

A vararg in Java is specified by three ellipsis (three dots) after the data type, its general form is

return_type method_name(data_type ... variableName){
 ..
 ..
}  

Need for varargs in Java

Prior to Java 5, in case there was a need of variable number of arguments, there were two ways to handle it

  • If the max number of arguments, a method can take was small and known, then overloaded versions of the method could be created.
  • If the maximum number of arguments a method could take was large or/and unknown then the approach was to put those arguments in an array and pass them to a method which takes array as a parameter.

These 2 approaches were error-prone as-

  • The addition of new argument may result in writing a new overloaded method.
  • Constructing an array of parameters every time makes it difficult to maintain.
Varargs in Java has distinct advantages over the above mentioned approach as it-
  • Offers a much simpler option to have a method with variable number of arguments.
  • Gets the work done with less code as no need to write overloaded methods.

Java varargs Example

public class VarargsExample {
 public void displayData(String ... values){
  System.out.println("Number of arguments passed " + values.length);
  for(String s : values){
   System.out.println(s + " ");
  }
 }
 
 public static void main(String[] args) {
  VarargsExample vObj = new VarargsExample();
  // four args
  vObj.displayData("var", "args", "are", "passed");
  //three args
  vObj.displayData("Three", "args", "passed");
  // no-arg
  vObj.displayData();
 }
}

Output

Number of arguments passed 4
var 
args 
are 
passed 
Number of arguments passed 3
Three 
args 
passed 
Number of arguments passed 0

In the example program displayData() method is called with different number of argument, first call with four arguments, then three arguments and then with zero arguments. All these calls are handled by the same method which takes varargs.

How does Java varargs work

When a method with variable number of arguments is called, Java compiler matches the argument from left to right, if there are any "normal" parameter then those are passed as it is, when the varargs parameter (which has to be the last parameter) is reached the remaining parameters are stored in an array which is referred by the name given to varargs and data type of the array is same as the data type of the varargs field.

From the above example you can see that length is used to find the number of arguments passed to the method. It is possible because arguments to the varargs are implicitly passed as an array.

Restriction with varargs in Java

  1. It is possible to have other parameters with varargs parameter in a method, however in that case, varargs parameter must be the last parameter declared by the method.
    void displayValues(int a, int b, int … values) // OK
    void displayValues(int a, int b, int … values, int c) // compiler error
    
  2. Another restriction with varargs is that there must be only one varargs parameter.
    void displayValues(int a, int b, int … values, int … moreValues) // Compiler error
     

Overloading varargs Methods in Java

It is possible to overload a method that takes varargs parameter though it may lead to ambiguity.
Varargs method can be overloaded by-

  • Types of its vararg parameter can be different.
  • By adding other parameters.

Overloading varargs method example

public class OverloadingVarargsExp {
 // Method which has string vararg parameter
 public void displayData(String ... values){
  System.out.println("Number of arguments passed " + values.length);
  for(String s : values){
   System.out.println(s + " ");
  }
 }
 
 // Method which has int vararg parameter
 public void displayData(int ... values){
  System.out.println("Number of arguments passed " + values.length);
  for(int i : values){
   System.out.println(i + " ");
  }
 }
 
 // Method with int vararg and one more string parameter
 public void displayData(String a, int ... values){
  System.out.println(" a " + a);
  System.out.println("Number of arguments passed " + values.length);
  for(int i : values){
   System.out.println(i + " ");
  }
 }
 
 public static void main(String[] args) {
  OverloadingVarargsExp vObj = new OverloadingVarargsExp();
  // four string args
  vObj.displayData("var", "args", "are", "passed");
  
  // two int args
  vObj.displayData(10, 20);
  
  // One String param and two int args
  vObj.displayData("Test", 20, 30);
 }
}

Output

Number of arguments passed 4
var 
args 
are 
passed 

Number of arguments passed 2
10 
20
 
 a Test
Number of arguments passed 2
20 
30 

Java varargs and overloading ambiguity

In some cases call may be ambiguous while we have overloaded varargs method in Java. Let's see an example.

public class OverloadingVarargsExp {
 // Method which has string vararg parameter
 public void displayData(String ... values){
  System.out.println("Number of arguments passed " + values.length);
  for(String s : values){
   System.out.println(s + " ");
  }
 }
 
 // Method which has int vararg parameter
 public void displayData(int ... values){
  System.out.println("Number of arguments passed " + values.length);
  for(int i : values){
   System.out.println(i + " ");
  }
 }
 
 public static void main(String[] args) {
  OverloadingVarargsExp vObj = new OverloadingVarargsExp();
  // four string args
  vObj.displayData("var", "args", "are", "passed");
  
  // two int args
  vObj.displayData(10, 20);
  
  // This call is ambiguous
  vObj.displayData();
 }
}

In this program when we make a call to displayData() method without any parameter it throws error, because compiler is not sure whether this method call is for displayData(String ... values) or displayData(int ... values)

Same way if we have overloaded methods where one has the vararg method of one type and another method has one parameter and vararg parameter of the same type, then also we have the ambiguity-

As Example-

displayData(int ... values)  

And 

displayData(int a, int ... values)

These two overloaded methods will always have ambiguity.

Points to note-

  • With Varargs in Java is has become simple to create methods that need to take a variable number of arguments.
  • In a vararg method call, arguments are inherently passed as an array itself.
  • If there are other parameters, then varargs parameter should be the last one.
  • In a method there can be only one varargs parameter.
  • vararg methods can be overloaded.
  • With overloaded vararg methods there may be ambiguity, in case method is called with no parameter at all.
  • With varargs it is possible to write the main method as public static void main(String ... args).

That's all for this topic Varargs (Variable-length Arguments) in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Why main Method static in Java
  2. Enum Type in Java
  3. Covariant Return Type in Java
  4. Method Overloading in Java
  5. Core Java Basics Interview Questions

You may also like-

  1. strictfp in Java
  2. static import in Java
  3. interface static methods in Java 8
  4. Constructor chaining in Java
  5. Lambda expression examples in Java 8
  6. ThreadLocal class in Java
  7. Difference between Checked exception & Unchecked exception
  8. LinkedHashSet in Java