1. Introduction
Varargs were introduced in Java 5 and provide a short-hand for methods that support an arbitrary number of parameters of one type.
In this article, we’ll see how we can use this core Java feature.
2. Before Varargs
Before Java 5, whenever we wanted to pass an arbitrary number of arguments, we had to pass all arguments in an array or implement N methods (one for each additional parameter):
public String format() { ... } public String format(String value) { ... } public String format(String val1, String val2) { ... }
3. Use of Varargs
Varargs help us avoid writing boilerplate code by introducing new syntax that can handle an arbitrary number of parameters automatically – using an array under the hood.
We can define them using a standard type declaration, followed by an ellipsis:
public String formatWithVarArgs(String... values) { // ... }
And now, we can call our method with an arbitrary number of arguments, like:
formatWithVarArgs(); formatWithVarArgs("a", "b", "c", "d");
As mentioned earlier, varargs are arrays so we need to work with them just like we’d work with a normal array.
4. Rules
Varargs are straightforward to use. But there’re a few rules we have to keep in mind:
- Each method can only have one varargs parameter
- The varargs argument must be the last parameter
5. Safe Use of Varargs
Using varargs can lead to so-called Heap Pollution.
Simply put, this means that Java handles varargs as generic Object instances which can lead to ClassCastExceptions later on.
This doesn’t mean that varargs aren’t safe. It’s safe when working with a concrete type like String, but utilizing generics might be not that straightforward.
As there’s a potential risk of a fatal runtime exception, the Java compiler or our IDE might show a warning like this one:
warning: [varargs] Possible heap pollution from parameterized vararg type T
If we ensure the method itself doesn’t do any malignant transformations or type-casts, we can use @SafeVarargs to suppress the warning.
6. Conclusion
Varargs can make a lot of boilerplate go away in Java.
And, thanks to their implicit autoboxing to and from Array, they play a role in future proofing our code.
As always, all code examples from this article can are available in our GitHub repository.