Tuesday, January 25, 2011

Send variable number of arguments to method. Another java 5 feature.

With variable argument feature we can send any number of arguments to same method. Useful when you are unsure that how many parameters will be passed to the method. One thing to keep in mind is that when we use this the variable or argument which represent varargs should be kept at last position of method, means it should be last argument to that method.

class VarArgTest{


private static double sum(double first, double second){

return first + second;

}


private static double sum(double first, double second, double third){

return first + second + third;

}


private static double sum(double first, double second, double... remaining){

double total = first + second;

for(double other : remaining)

total += other;

return total;

}

public static void main(String[] args){

System.out.printf("Sum of two: %f%n", sum(2.8, 3.7));

System.out.printf("Sum of three: %f%n", sum(2.8, 3.7, 4.4));

System.out.printf("Sum of five: %f%n", sum(2.8, 3.7, 4.4, 7.2, 9.1));

}

}


To compile:

javac VarArgTest.java

To run:

java VarArgTest

No comments: