Java varargs With Examples

Java varargs was introduced in Java 1.5. Java varargs is also known as java variable arguments.

Java varargs

varargs in java enables a method to accept variable number of arguments. We use three dots (…) also known as ellipsis in the method signature to make it accept variable arguments. For example;

Important points about varargs in java

Few points to know about varargs in java are;

  1. We can have only one varargs in the method.
  2. Only the last argument of a method can be varargs.
  3. According to java documentation, we should not overload a varargs method. We will see why it’s not a good idea.

How java varargs work?

When we invoke a method with variable arguments, java compiler matches the arguments from left to right. Once it reaches to the last varargs parameter, it creates an array of the remaining arguments and pass it to the method. In fact varargs parameter behaves like an array of the specified type.

If you will look at both sum and sumArray methods, you will see that the implementation body is exactly same. So we should use varargs when API offers them, for example java.io.PrintStream.printf() method but we should not take it as a replacement for array.

Why we should not overload varargs method

Let’s look at an example why overloading java varargs method is not a good idea.

In above example, you will notice that compiler will not complain when we overload methods with varargs. But when we try to use it, compiler get’s confused which method to use when mapping the second argument.

If there is only one argument, compiler is smart to use first method because it can work with minimum one argument but second method needs at least two arguments. Below image from Eclipse shows the error message as The method sum(int, int[]) is ambiguous for the type VarargsExample.

java-varargs

That’s all about java varargs. It’s good to know feature but you don’t need to use it when writing code yourself.

Reference: Official Documentation

By admin

Leave a Reply