Ads

Saturday, 28 October 2017

What is VarArgs?

Variable Argument


VarArgs is also known as Variable Argument.  

The Variable Argument allows the method to accept zero or multiple arguments. Before varargs either we use the overloaded method or take an array as the method parameter but it was not considered good because it leads to the maintenance problem. If we don't know how many arguments we will have to pass in the method, varargs is the better approach.

The Advantage of Varargs We don't have to provide overloaded methods so less code.

Syntax is as follows: 

return_type method_name(data_type... variableName){} 

Example of Varargs in java: 

class VarargsEx
{
    static void display(String... values)

    {
       System.out.println("display method invoked ");
    }

   public static void main(String args[])

   {
      display();
      display("I ","Am",".....","varargs");   

   }    



Post a Comment

Click Here