Tuesday, March 6, 2007

Variable number of arguments in Java

Did you know that java too supports variable number of arguments?

Here's an example.

Try it.

class test{
public static void main(String args[]){
System.out.println("The sum is " + calculateSum(1,2,3));
}

private static int calculateSum(int... values){
int sum = 0;
for (int counter = 0; counter < values.length; counter ++){
sum = sum + values[counter];
}
return sum;
}
}


It works with both primitive data types and objects.

3 comments:

VV said...

Ya... thats good. Is there any specific reason for you to say that "Java too supports". Was c++ in your mind and i guess how variable no of arguments is handled in both these languages are different...

Let me know...

Antony Vincent Pandian.S. said...

Yeah. I had C++ in my mind while typing that.
he handling of variable number of arguments is different in both c++ and java. In C++, we use that va_args and other stuff (i dont remember them) but in java, it is considered as a dynamic array. Based on the number of inputs, the array is created and the operations are done.

Koushik said...

Great.. to read your blog. this feature works only java-1.5+ I guess..