Variable arguments or varargs methods in java

Java variable arguments was introduced in java 5 and it allows methods to take as many number of arguments you want.

Syntax:

We use three dots (…) also known as ellipsis to define variable arguments.

There are some points which you need to keep in mind while using varargs methods:

  1. You can have only one variable arguments (ellipsis) in one method
  2. varargs should be last parameter in the method, otherwise method won’t compile.

Why to use variable arguments or varargs methods:

There are two alternatives which can be used which developers used before java 1.5

  1. Method overloading
  2. Passing array to the method

Method overloading may not be good idea because you don’t know number of methods you need to overload.You can pass arguments in the array but why don’t we can directly use varargs method and let compiler create array for us.

How varargs works internally.

While invoking varargs method, compiler matches argument from left to right, Once fixed number of arguments are matched, rest all arguments are created as array and passed to method.
For example:

Lets say you have method signature as below:

and you invoke this method as

then “test” and 1 will be passed as normal parameters and 2,3 and 4 will be passed as array.

Java variable arguments or varargs example:

When you run above program, you will get below output:

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *