Search This Blog

Wednesday 4 January 2017

Variable argument or varargs in Java

Variable argument or varargs in Java 

Variable argument or varargs in Java allows you to write more flexible methods which can accept as many argument as you need. variable arguments or varargs were added in Java 1.5 Variable arguments is a  useful for a developer. Some time we have a scenario that one method can take variable number of argument  and now with varargs from language makes it much easier.

Variable arguments before Java 1.5 
Prior to Java 1.5 if a Java programmer needs to send multiple arguments to a method, they mainly have two choices to :

1. Either overload the method.
2. Take an array or Collection and pass the no of argument wrapped in array or Collection like List, Set or Map.

The real challenge for a developer comes when the developer is not aware about the number of arguments to handle and how many overloaded methods will be created. This will result in long and clumsy code, which again can be error prone if the developer has missed including the method with specific number of argument in the code.
This is where in varargs comes into picture.

varargs or variable arguments makes it possible for the developer  to call one method with variable number of argument; means define only one method and call that method with zero or more argument.



Syntax:
             type … variable Name.

Ellipses stands for variable argument java treats variable argument as an array of same data type. 3 dots is used to denote variable argument in a method and if there are more than one parameter, varargs arguments must be last, as better listed below

Some points which should be taken care when use varargs:
  1.       Ellipse can be used once in method parameter list.
  2.       Ellipse with type must be used in parameter list at the end of the method



Example to illustrate Varargs
public class Example01 {
      public static int add(int ...var){
            int sum=0;
            for(int i:var)
                  sum+=i;
     
      return sum;
}
      public static void main(String[] args) {
            System.out.println("Sum of 1 and 2 is = " +add(1,2));
            System.out.println("Sum of 1, 2 and 3 is = " + add(1,2,3));
            System.out.println("Sum of 1, 2, 3 and 4 is = "+add(1,2,3,4));
      }
}
Output of the Code

Variable argument or varargs in Java
Variable argument or varargs in Java




15 comments: