Translate

Sunday 21 December 2014

Variable Length Arguments in java

Java supports variable length argument of one data type. That is we don't need to define number of arguments when its variable for one type of data-type.

For example:-
class Calculator
{
    public int sum (int... a)
    {
        int total=0;
        for(int i=0; i < a.length; i++)
                    total+= a[i];
        return total;
    }
}

A variable length argument allows us to pass any number of arguments while calling the method.
There can be only one variable length argument in a method and if  present it must be the last parameter.

for example
public void method(String S, float f, int... a)
{
   .......
}

Variable length argument reduces number of method if method overloading is being done on the basis of number of parameters.

No comments:

Post a Comment

Total Pageviews