Friday, September 23, 2011

Variable argument or Varargs methods from Java 5 with Example - Programming Tutorial

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 along with great language features like Java Enum, Generics, auto boxing and various others. Variable arguments a relatively small feature but useful for a developer who has been well aware about method and array. 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. In this Java tutorial we will see How variable arguments makes it easy to write convenient method which can accept any number of arguments,  perfect candidates are sum() and average() kind of methods.

This article is in continuation of exploring features of Java programming language. I have already covered fork-join framework from Java 7 and automatic resource management or ARM blocks, if you haven't read them already you may find them useful.

Variable arguments before Java 1.5 

Prior to Java 1.5 Java programmer mainly have two choices to :

variable arguments or varargs in Java 5 with example program
1. Either overload the method.
2. Or can take an array or Collection and pass the no of argument wrapped in array or Collection like List, Set or Map.

But the problem with this is to if he is overloading the method and he don’t know about how many arguments he has to handle how many method will be created in the code i.e the code will become clumsy or if he has not created sufficient method then again the codes need to be modified and complied so it’s become repetitive task which is not a good programming practice and requires more maintenance .Now we can go for array also but ks why not we give this task to Java for creating an array and store the element in to that array to internally handle  and let make programmer free of this, I guess with this thought  varargs comes into existence.
varargs or variable arguments makes it possible for us to call one method with variable number of argument; means define only one method and call that method with zero or more than zero 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

Real world Example of varargs in Java

First we look one real world scenario suppose we go one college and take admission on that college now its not really decided that admission will be done for how many student may be 50 student will come or 100 or more than that at a time. So college is one class and Admission is one procedure or method that takes no of student as an argument .So in that method we can use varargs or variable arguments.

/**
 * Simple real world example of variable argument methods
 */

public class college {

public void admission_method (int... no_of_student) {
 
//rest of code for processing

}

}


Simple java variable argument example:

Let consider one simple example of finding the multiplication of n number. First we will try to solve this problem using method overloading


/**
 * Java Program which tries to implement variable argument method using
 * method overloading. This started get clumsy once number of parameter exceeds
 * five.
 */

class  VarargsExample{

 
public int multiply(int a,int b){ return a*b;}

 
public int multiply(int a,int b,int c){ return (a*b)*c;}

 
public int multiply(int a,int b,int c,int d{ return (a*b)*(c*d);}

}

If we use method overloading same method will be repeated again and again and its not worth after four or five parameters. now will use array also to solve this problem of variable arguments:

Let see how:

/**
 * Java Program which tries to implement variable argument method using
 * method overloading. This started get clumsy once number of parameter exceeds
 * five.
 */

class  VarargsExample{

 
/*
   * @return multiplication of all numbers in array
   */

 
public int multiply(int[] numbers){
   
int result = 1;
   
   
for(int number: numbers){
      result= result
*number;
   
}
   
   
return result
 
}
}

Here we need to create an integer array and  pass that array to the method and then iterate the array and get result .
We can simplify this with variable argument provided by java 5 where creation of array will be done internally and our task become easier.

/**
 * Java Program which uses varargs feature to accept variable number of
 * arguments. variable arguments are implemented using anonymous array so if
 * another method with exact same signature except array in place of varargs will result
 * in compiler error.
 */

class  VarargsExample{

 
/*
   * @ return multiplication of all numbers in array
   * if varargs method accept more than one parameter than varargs arguments
   * must be last parameter.
   */

 
public int multiply(int... numbers){
   
int result = 1;
   
   
for(int number: numbers){
      result= result
*number;
   
}
   
   
return result
 
}
}


Important points related to variable argument or varargs methods:


1) Every call to varargs method require an anonymous array to be created and initialized which could affect performance in time critical application. There is an alternative of varargs method to achieve better performance. suppose you have a variable argument method sum(int... num) and its called with 2 parameters on 90% of time. In order to avoid array creation and initialization you can use method overloading in Java to provide two versions of sum() which accept int instead of varargs. here is an example of better performance alternative of varargs for 90% of time

public int sum(int a);
public int sum(int a, int b);
public int sum(int... num);

Now 90% of time method without varargs will be invoked and 10% of time method with variable argument will be invoked.

2) An example of variable argument method from JDK is Arrays.asList(T... args) which was used to convert array to ArrayList before JDK 1.5 but retrofitted to support variable argument in JDK 1.5. Now you can also invoke this method by just passing as many Strings or object as you want and creating a List representation on the fly. Its one of the quickest way to convert Strings into List e.g.

List listOfString = Arrays.asList("Red", "White", "Blue");

3) Another example of varargs methods are in java.lang.reflect package. Reflection uses lot of variable argument method to call overloaded method dynamically. Method class used variable argument to get correct version of overloaded method. Method.getMethod(String name, Class... parameterTypes) uses last argument as parameter type which is a variable argument and can accept any number of parameters. This is used to invoke method by name using reflection.

4) If you are working on a legacy project which is not running on Java 1.5 or higher, you can still implement variable argument methods by using Anonymous array or Collection classes like ArrayList or HashSet. Both array or Collection classes can wrap number of argument into one. Using Collection framework also has an added advantage in terms of rich API e.g. meaningful toString() method, iteration support etc.

That’s all on variable arguments or varargs in Java, Please let me know how you guys use variable arguments and what your opinion about it is.

Related Java Tutorials

3 comments :

Peter Lawrey said...

You can specify that there must be at least one argument. Varags has a minimum of zero. e.g.

double multiply(double d, double... ds)

Jimmy said...

is it mandatory to have variable argument parameter list as last argument in method? Why we can not have first parameter of any method as variable argument list in Java ?

Anonymous said...

@Jimmy, yes its mandatory for variable argument to be as last argument in method, syntax is imposed by Java programming language.Anyway I still wonder why Java takes so long till 1.5 to include variable arguments or enum which is already available on C and C++?

Post a Comment