Varargs in Java

Varargs or variable arguments was a feature  introduced in Java 5 to reduced code bloat. Java has been criticized as a very noisy language requiring lot of cermonial code to function properly. Varargs is one of the ways to make your methods more flexible and reduce the amount of boilerplate code you have to write.

What is Varargs feature?

Varargs feature allows you to pass variable number of arguments to a method. By using vargs feature you can pass zero to unlimited number of arguments of the same type to a method.

Suppose you want to say hello to all the visitors that come to your house in a single method call. Something along the lines –

Since the guests may come in groups of one, two or more you need to devise sayHello, sayHello2, sayHello3 – a clear case of code duplication. One of the guiding priniciples in software engineering is Don’t Repeat Yourself and writing such methods would be a blatant violation of DRY principle.

As an alternative you may pass a Java collection to a method and the method can then operate on individual Java elements. Since we have not yet covered Java Collections, we will not go into the code. But this approach of using Java Collections is so obvious and mandatory that Java provides a shortcut of using it. This shortcut is called varargs. In fact any argument with varargs can be treated as a fixed length array.

Syntax of Varargs

The symbol for varargs in Java is ellipsis i.e … . The three consecutive dots indicate that a variable, indeterminate number of arguments are occuring. The ellipsis is preeceded by the type of the variable as shown below

Let’s re-write our method to say hello to any number of guests in a single method.

The output of the above code is –

As you can see Java interpreted … to be a variable length argument. We used enhanced for loop to iterate over the elements passed to the method and say hello to all guests. Let’s now look at the another, often cited example of varargs.

Another Example of Varargs

We now use variable arguments to write a method that can multiply zero or more numbers to 1 and return the result –

The output of the code is

Note that it is valid to pass zero or one arguments. It may not make much sense to multiply “no numbers” or a number with one, but from Java’s feature perspective it is allowed.

Rules for Varargs

The following rules applyto varargs usage –

  1. Can be used ONLY in methods or constructors
  2. Are allowed in constructors
  3. Cannot be used for variable declaration
  4. Any method can have maximum ONE varargs argument
  5. The varargs argument must be the last argument in the method arguments list

Some More Examples of Varargs

Here is a valid example of method using varargs –

And here are some examples of invalid usage

That’s all you need to know about varargs for using them effectively.

Leave a comment

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