No comments yet

Var-args in Java

[Social9_Share type="horizontal"]

Var args in Java

Whenever, I want to pass a list of similar values as a parameter in a method, I have to use an array. In case of an array, the size is fixed. So I have to use the inbuilt API classes from java.util like List or Set.

Instead, lets us try to use Var-args – also called as variable argument list as a parameter.Let me discuss on

What is Var-args ?

Var args means Variable argument list. This specifies a flexible array whose size can vary from size 0 to any number.

Syntax and Method Signature

While using var-args in your method, you need to follow certain rules like,
• In a method you can have only one var-arg parameter.
• The var-arg parameter should be last argument in your method.
• The data type must be followed by three dots (int… marks) where marks is a variable argument.


Here marks is a var-arg parameter. This method can be called in different ways like,

So, the array size can vary from 0 to any number.

Wrong Method Signatures

The below given method signatures will give a compiler error

A simple Example

Let’s see a simple program using var-args. I have a method calculateSum(String name, int... marks)

This method can be called in many different ways like

If you notice, the array size varies in each and every method call. I am using for-each to iterate the array. For the first method call the array size will be zero. So, it will print the name and then the sum as 0.

The complete example is given below.

Which method will be called ?

Assume, I have two overloaded methods, that has similar parameters where one method takes var-args –

When I am calling the method as calculateSum("Tom", 90) Which method will be called?
JVM will call the method with the matching parameter only(the second one).

The modified program is given below.

When to use var-args and when to use overloading?

Now,that I know overloading and varrags. In which scenario, should I use Varargs and when should I use overloading?
Lets discuss that.

Use Varargs :
• when the functionality is same and the parameter values are different
eg. Calculation of total sum of marks – the logic is same, but the number of marks may vary.

Use Overloading :

• when the number of parameters are different and also the functionality is different
eg. Area calculation for different shapes – the parameters differ and the functionality also differs.

Quick Note

The main method public static void main(String[ ] args) can also be represented using var-args as
public static void main(String... args)

Guys. Try this and give me your views.

To learn how to add objects to an ArrayList click here.

Till then,
Happy Learning.

Post a comment