Creating variable argument function in Java

Variable argument functions are those functions which can take a variable number of arguments. One can invoke such functions by passing either one, two, three or more arguments depending on the requirement. For example we can define a function average to return average of two numbers when called with two arguments like average(2,3), three numbers when called with three arguments like average(2,3)Β and so on.

Creating a variable argument function is very simple- just give three dots between the data type and the argument name in the argument list. The argument would then be used like an ordinary array and would be loaded automatically with the respective arguments given at the point of invocation. A Java program to calculate the average of variable number of arguments using variable argument function is as follows:

class VariableArgumentFunction{
    public static float average( float ... a ){
        float sum=0f;
        for( int i =0 ; i < a.length ; i++ ){
            sum += a[ i ];
        return sum/a.length;
    public static void main(String [] args){
        System.out.println( "Average of 1,2 is " + average( 1, 2 ) );
        System.out.println( "Average of 1,2,3 is " + average( 1, 2, 3 ) );
        System.out.println( "Average of 1,2,3,4 is " + average( 1, 2, 3, 4 ) );

Notice the three dots between float and a on line number 2. Also notice that in the function main() we are invoking the function average (which is out variable argument function) three times with one, two and three arguments respectively. The rest of the program is pretty self-explanatory-the average is being computed by dividing the sum of all the numbers by the length of the array.
Note that when using variable a variable argument function you may have other argument(s) before the variable argument, but no argument can be given after the variable argument because in that case it won’t be possible to ascertain where the variable arguments is finishing and the normal arguments are starting.

One thought on “Creating variable argument function in Java

  1. Pingback: Enhanced for loop |

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.