Saturday, 15 March 2014

3 dot (…) method or Varargs in Java


To see explanation please click here

Varargs was added in Java 5 and the syntax includes three dots ()

         These functionality enables to write methods/functions which takes variable length of arguments. For example the popular print() method in Java. We can call print() method with multiple arguments.Some time we have a scenario that one method can take variable number of argument  and now with varargs from language makes it much easier. In this Java tutorial we will see How variable arguments makes it easy to write convenient method which can accept any number of arguments,  perfect candidates are sum() and average() kind of method

Following is the syntax of vararg method.


Syntax:- 

            return_type MyMethod(type...Variable_name)


Notice the dots ... in above code. That marks the last argument of the method as variable argument. Also the vararg must be the last argument in the method.
It means that zero or more String objects (or an array of them) may be passed as the parameter(s) for that function.


Important Note 1: 

The parameter(s) passed in this way is always an array - even if there's just one. Make sure you treat it that way in the method body.

Important Note 2: 

 The parameter that gets the ... must be the last in the method signature. So, myMethod(int i, String... strings) is okay, but myMethod(String... strings, int i) is not okay.


Program:-

Program
Program for 3 dot (...) method













 

Output
Output of Above program
            In above code, the add() method is taking variable arguments and is being called from main method with number of arguments. In its every call we use different arguments. This can be done with the help of method overloading up to some extent. But 3 dot (…) method is best solution for it. By using this type of method you can implement addition, subtraction, multiplication, division,etc.
To see the explanation of above program please see video. It helps you to understand the concept easily.


You are always welcome to ask any doubts if you have. Thanks.

No comments:

Post a Comment