Saturday, June 9, 2007

Passing unspecified number of arguments to a method in Java

Java provides a feature to pass unspecified number of argument to a method. It treats the variable-length argument list as an array. This is represented by argument type followed by three dots in the declaration of the method. This facility is included from JDK 5.0.
An example code is given below..

public int add(char a,int... num ) //variable length argument
{
int no=num.length;
int sum=0;
for(int i=0;i!=no;i++)
sum+=num[i];
sum+=a;
return sum;
}

public static void main(String[] args) {
Main m=new Main();
System.out.println(m.add('A',10,20));
System.out.println(m.add('A',10,20,30));
}

No comments: