Thursday, July 7, 2016

Variable Argument Methods in Java with Example(Varargs)

In java we call a method with its signature by passing the suitable arguments it takes. So the calling function must know the number of arguments and the types of arguments the called function will take. But, in some scenarios we need to call a function and we are not sure about the number of arguments the method will take or in other words we can say that the called method is unpredictable in respect of the number of arguments and the type of the arguments. The second scenario is that sometimes we call a function in the class which just performs some kind of operation(let's say multiplication) on the number of arguments that we pass to that function. Hence, we need to pass the each number to that method but it is made easy by variable arguments that while catching those arguments we don't need to specify the type and name of each of those arguments. Rather we can catch all of them in a variable argument. Below is an example of simple code snippet which is not using varargs.

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

Here, we need to declare the type and name of the argument for each variable. Instead of it we can do it using varargs like follows:

public int multiply(int... numbers){
int result = 1;

for(int number: numbers){
 result= result*number;
}

return result
}

Here , in this code each and every number is catched in the numbers argument and is fetched one by one using the fore loop.

So, the biggest benefit of using it is to avoid method overloading for some scenarios.

Another example:

class VarargsExample2{  
   
 static void display(String... values){  
  System.out.println("display method invoked ");  
  for(String s:values){  
   System.out.println(s);  
  }  
 }  
  
 public static void main(String args[]){  
  
 display();//zero argument   
 display("hello");//one argument   
 display("my","name","is","varargs");//four arguments  
 }   
}  

Output:
display method invoked
display method invoked
hello
display method invoked
my
name
is 
varargs

Some points to remember about varargs:

*There can be only one variable argument in the method.
*Variable argument (varargs) must be the last argument.

Note: public static void main(String args[]) is the biggest example of varargs as it takes a undefined number of runtime arguments.

No comments:

Post a Comment