Using Ellipsis to A!ccept Variable Number of Arguments


A method can receive a variable number of arguments with the use of ellipsis (three consecutive dots: …) In order to do so, the data type of the variable number of arguments which can be even a reference type is stated followed by the ellipsis and an identifier. This type can be used not more than once in a method header and should be the last of all parameters. Following lines show a few valid and invalid method declarations that use variable length argument lists.
public void meth ( int… a) // valid
public void meth (double a, int… b) // valid
public void meth ( int… a, int b) // invalid- Ellipsis may be used towards the end only
public void meth ( int… a, double… b) // invalid – More than one variable length parameter list may not be used
public void meth ( Student… a) // valid – Reference types are also allowed
public void meth( int[]… a) // valid – reference types are also allowed
The arguments received are stored in an array of the same data type as specified in the method header having a length equal to the number of arguments passed. Therefore, those elements can be accessed as we access an array passed to an array type parameter. Here is an example of a class Add containing a method addVariable() which takes variable number of arguments, add them and displays the result. This method is invoked through the main method with 0, 1 and 2 arguments.
public class Add {

Public static void main(String[] args) {
addVariable();
addVariable(1);
addVariable(3, 4);
}

Public static void addVariable(int… a) {
int sum = 0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
}
System.out.println(a.length + ” arguments received whose sum is ” + sum);
}
}

Here is the output of this program.
0 arguments received whose sum is 0
1 arguments received whose sum is 1
2 arguments received whose sum is 7
The method taking variable arguments is called only when no exact match of arguments occur for a given method call. For example if we had a method that accepts a single int argument in the above class, the method call addVariable(1) would invoke this particular method rather than the one taking variable number of arguments. Verify this fact yourself by modifying the code above.
Author: , 0000-00-00