Variable-Length Arguments Method in short varargs methods, Such methods usefulness comes into picture when you have a method that can accept a variety of arbitrary data types.
The syntax of a method that accepts a variable number of arguments is as follows:
returnType methodName ( typeName … paraName)
{
………………..
}
Here, paraName is the name of the parameter representing an array of typeName and the ellipsis (m) between typeName and paraName specifies that paraName is actually to be treated as array of zero or more elements of type typeName. Keep in mind that only one variable length parameter may be specified in a method, and may only appear on the last parameter in the list. Regular parameters may precede it.
Now let us consider a program to understand the concept of variable-length arguments. For this, we make a program to calculate average of integer numbers.
public class VarargsMethods
{
public static void main(String[] args)
{
average(15,100);
average(15,100,150);
average(15,100,105,210);
}
static void average(int...num)
{
double sum=0, avg;
int i;
for( i=0; i<num.length; i++)
{
sum += num[i];
}
avg = sum/num.length;
System.out.println("Average = " +avg);
}
}