What are varargs in Java, and how does the compiler turn a varargs call into an array?
Varargs is a way to write a method that takes any number of arguments of one type. You write three dots after the last parameter type, and that parameter becomes an array inside the method.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println("sum(1, 2, 3) : " + sum(1, 2, 3));
System.out.println("sum(10) : " + sum(10));
System.out.println("sum() : " + sum());
System.out.println("length : " + sum(1, 2, 3, 4, 5));
}
// The three dots make this method take any number of ints.
static int sum(int... values) {
int total = 0;
for (int index = 0; index < values.length; index++) {
total = total + values[index];
}
return total;
}
}
Here is what the compiler does with it. When you call the method with a list of values, the compiler builds a new array of that type, puts the values into it, and passes the array as a single argument. So the call sum(1, 2, 3) really becomes the call sum(new int[] {1, 2, 3}).
That is why a varargs parameter has to be the last one in the list. There is nowhere after it to put another argument, so the compiler cannot work out where the array should stop and the next argument should begin.
You can also pass an array directly, and then no new array is built. So sum(values) where values is already an int[] is the same as the spread version, and it is the cheaper of the two calls.
The next question in this topic looks at the two edge cases that cause trouble.