Tuesday, April 29, 2008

How to pass unspecified number of arguments to a method

JDK 5.0 provides a feature to pass unspecified number of argument to a method. Java 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.

The method int sum(int…numbers) can take any number of parameters of type integer.

public int sum(int...numbers) {

int sum=0;
for (int d : numbers )
sum =sum + d;
return sum;
}

public static void main(String[] args) {
int i=3;
int j=6;
int k=9;
System.out.println("Sum of two numbers"+sum(i,j));
System.out.println("Sum of three number"+sum(i,j,k));
}
}

For more details: Java Tips

No comments: