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;
1 2 3 4 5 |
public static int sum(int i, int...js ){ //do something } |
Important points about varargs in java
Few points to know about varargs in java are;
- We can have only one varargs in the method.
- Only the last argument of a method can be varargs.
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
//method with variable arguments public static int sum(int i, int...js ){ int sum = i; for(int x : js){ sum+=x; } return sum; } //method with same implementation as sum with array as argument public static int sumArray(int i, int[] js ){ int sum = i; for(int x : js){ sum+=x; } return sum; } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.journaldev.misc; public class VarargsExample { public static void main(String[] args) { System.out.println(sum(1)); System.out.println(sum(1,2)); //compiler error, ambiguous method } public static int sum(int i, int...js ){ System.out.println("sum1 called"); int sum = i; for(int x : js){ sum+=x; } return sum; } public static int sum(int i, int k, Object...js ){ System.out.println("sum2 called"); int sum = i+k; for(Object x : js){ sum+=1; } return sum; } } |
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
.
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