MOCKSTACKS
EN
Questions And Answers

More Tutorials









Java Variable Arguments (VarArgs)


In the previous tutorial, we discussed how we can overload the methods in Java.

Now, let's suppose you want to overload an "add" method. The "add" method will accept one argument for the first time and every time the number of arguments passed will be incremented by 1 till the number of arguments is equaled to 10.

One approach to solve this problem is to overload the "add" method 10 times. But is it the optimal approach? What if I say that the number of arguments passed will be incremented by 1 till the number of arguments is equaled to 1000. Do you think that it is good practice to overload a method 1000 times?

To solve this problem of method overloading, Variable Arguments(Varargs) were introduced with the release of JDK 5.
With the help of Varargs, we do not need to overload the methods.

Syntax :
/*
public static void foo(int … arr)
{
// arr is available here as int[] arr
}
*/

foo can be called with zero or more arguments like this:

foo(7)
foo(7,8,9)
foo(1,2,7,8,9)


Examples


class calculate {

    static int add(int ...arr){
        int result = 0;
        for (int a : arr){
            result = result + a;
        }
        return result;
}

public static void main(String[] args){
    System.out.println(add(1,2));
    System.out.println(add(2,3,4));
    System.out.println(add(4,5,6));
}
}

Output

3
9
15


Conclusion

In this page (written and validated by ) you learned about Java Variable Arguments (VarArgs) . What's Next? If you are interested in completing Java tutorial, your next topic will be learning about: Java Recursion.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.