Var-args

Var-args feature were added in java 5. This feature allow to define a method which can take any number of arguments. For example say we have to write one method which will take some number then that method will calculate mean of those numebr. Without var-args feature, this program can be written using array.

Example:


	  // file: var.java 
// www.jgyan.com
class var
{
public static void main(String arg[])
{
int arr[]={12,23,10,20,15};
mean(arr);
}
static void mean(int [] a)
{
int i, sum=0;
for(i=0; i<a.length;i++)
sum=sum+a[i];
System.out.println("Mean:"+(sum/i));
}
}
/* Output:
mean:16
*/

Above example an array is passed to method mean. We can't pass integer number directly into mean method, first those number need to be stored in array then that array is passed in the method.


Same example with var-args feature: By using var-args no need to create an array. "..." is used to create a variable length argument. At the time of method calling, arguments specified in method are internally converted into array. That conversion is done by java so programmer no need to write code for that task.


Example


	  // file: var1.java
// www.jgyan.com
class var1
{
public static void main(String arg[])
{
mean(12,23,10,20,15);
}
static void mean(int ... a)
{
int i, sum=0;
for(i=0; i<a.length;i++)
sum=sum+a[i];
System.out.println("Mean:"+(sum/i));
}
}
/* Output:
mean:16
*/