You are here:   HomeJava ProgrammingInheritancevarargs - Variable-Length Arguments Method in Java Example
by Dinesh Thakur Category: Inheritance

Variable-Length Arguments Method in short varargs methods, Such methods usefulness comes into picture when you have a method that can accept a variety of arbitrary data types.

The syntax of a method that accepts a variable number of arguments is as follows:

returnType methodName ( typeName ... paraName)

{

....................

}

Here, paraName is the name of the parameter representing an array of typeName and the ellipsis (m) between typeName and paraName specifies that paraName is actually to be treated as array of zero or more elements of type typeName. Keep in mind that only one variable length parameter may be specified in a method, and may only appear on the last parameter in the list. Regular parameters may precede it.

Now let us consider a program to understand the concept of variable-length arguments. For this, we make a program to calculate average of integer numbers.

public class VarargsMethods

{
     public static void main(String[] args)
     {
       average(15,100);
       average(15,100,150);
       average(15,100,105,210);
     }
     static void average(int...num)
     {
        double sum=0, avg;
        int i;
        for( i=0; i<num.length; i++)
            {
                 sum += num[i];
            }
        avg = sum/num.length;
        System.out.println("Average = " +avg);
     }
}

varargs  - Variable-Length Arguments Method in Java Example





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Popular Article