Sunday, August 8, 2021

Variable argument and Varargs methods in Java with Example - Programming Tutorial

Variable argument or varargs in Java allows you to write more flexible methods which can accept as many arguments as you need. variable arguments or varargs were added in Java 1.5 along with great language features like Java Enum, Generics, autoboxing and various others. Variable arguments a relatively small feature but useful for a developer who has been well aware of method and array. Some time we have a scenario that one method can take a 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 the 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 methods 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 compiled so it’s become a 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 into 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 the 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 a result .  We can simplify this with variable argument provided by java 5 where the 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 the variable argument or varargs methods:

1) Every call to varargs method requires an anonymous array to be created and initialized which could affect performance in time-critical applications. There is an alternative of varargs method to achieve better performance. suppose you have a variable argument method sum(int... num) and it's called with 2 parameters on 90% of the 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 a better performance alternative of varargs for 90% of the time

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

Now 90% of the time method without varargs will be invoked and 10% of the time method with a 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 the variable argument in JDK 1.5. Now you can also invoke this method by just passing as many Strings or objects as you want and creating a List representation on the fly. Its one of the quickest ways to convert Strings into a List e.g.

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

3) Another example of varargs methods are in java.lang.reflect package. Reflection uses a lot of variable argument methods to call overloaded method dynamically. Method class used variable argument to get the correct version of overloaded method. Method.getMethod(String name, Class... parameterTypes) uses the 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 a number of arguments into one. Using the 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

6 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++?

Anonymous said...

One of the best example of variable argument method is public static void main(String... args), yes you can write your favourite main method public static void main(String args[]) like that. Those three dots denotes variable arguments. Just remember that variable argument has to be last argument and I think you're only allowed one vararg per method/constructor argument list.

Anonymous said...

Just remember that variable argument must be the last argument otherwise Java will not know where to finish. On the same line you can have only one variable argument per method/constructor in Java.

Detoxic Spirit said...

My Conclusion after connecting the links from where i came xD

public static final synchronized strictfp void main(String... s) {
concat(2, 4, 7, "x", 'd');
}

@SafeVarargs
static void concat(T... x) {
/*
* for (T z : x) System.out.print(z);
*/
System.out.println(Arrays.asList(x));
}


Nice tutorials x)

Post a Comment