Using varargs - RichardDanielOliva/java-learning-wiki GitHub Wiki

Varargs were introduced in Java 5 and provide a short-hand for methods that support an arbitrary number of parameters of one type.

Example

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) { ... }

Use of Varargs

Varargs help us avoid writing boilerplate code by introducing the 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")

Important note

Varargs are arrays so we need to work with them just like we'd work with a normal array.

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

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.

References

https://www.baeldung.com/java-varargs