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.

Follow me

Vinay Singh

Computer Teacher at Saint John's Academy
I am a GNU/Linux enthusiast and a computer science teacher by profession based at Allahabad, India. My hobbies include reading (mostly computer related stuff) and photography.
Follow me

Latest posts by Vinay Singh (see all)

One thought on “Creating variable argument function in Java

  1. Pingback: Enhanced for loop | www.VinaySingh.info

Leave a Reply