Wednesday, March 10, 2010

Defining functions with varying parameters

Ellipsis concepts in java helps to define a function with varying parameters.Following example will help u to understand this.
public class VaryingParametersTest {
   public static void main(String args[]) {
           System.out.println(add(1, 2, 3));
           System.out.println(add(1, 2, 3, 4, 5, 6));
   }

   public static int add(int... values) {
        int sum = 0;
        for (int val : values) {
            sum = sum + val;
        }
        return sum;
   }
}

2 comments:

  1. u can also access the values as array:

    values[0],values[1] and so on.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete