Thursday, July 5, 2007

Variable Number of Arguments

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.

No comments: