Friday, 1 July 2016

java varargs | Method Overloading using varargs 1.5 example

When your performing method overloading different versions of methods will be executed depending upon each method call. Until java 1.4 version we can't declare a method with variable number of arguments, if there is any change in number of arguments compulsory we should declare a new method. This approach increases length of the code and reduces readability. Suppose the following method overloading needs to change every time when the number of arguments increased i.e when overloading is done.


sum( int, int) // will add two numbers

sum(int, int, int) // add three numbers

sum(int, int, int, int) // add four numbers



To resolve these problem SUN peoples introduced var-arg method in 1.5 version. Hence from 1.5 version on words we can declare a method with variable number of arguments such type of methods are called var-arg method. We can declare var-arg method as follows

methodName( type...variable)

 Example: m1(int...x); , we can invoke this method by passing any number of int values

 Internally var-arg method is implemented by using single dimensional arrays concept. Hence with in the var-arg method we can differentiate arguments by using index.



class Test
{
public static void sum(int...x)
{
int total=0;
for(int y:x)
{
total=total+y;
}
System.out.println(" The sum:" +total);
}
public static void main(String args[])
{
sum();
sum(10,20);
sum(10,20,30);
sum(10,20,30,40);
}
}


The above program give the following output

The sum:0
The sum:30
The sum:60
The sum:100

Rule For Varargs

1.We can mix var-arg parameter with normal parameter also
       Ex: m1( int x, string...y);
2. If your mixing var-arg parameter with general parameter them var-arg parameter should be last parameter.
     Ex: ma(int...x, string y) gives an error
3. In any var-arg method we can take only one var-arg parameter
    Ex: ma(int...x, string...y);  gives an error
4. In general var-arg method will get least priority i.e of no other method, then only var-arg method will get
    chance. This is similar to default case inside switch.

0 comments:

Post a Comment

Advertisement

Find Us On Facebook

C Programming

More

C++ Tutorial

More

Java Tutorial

More

Computer Basics

More

MS Office

More

Database Management

More
Top