Varargs in Java
A varargs parameter, written with three dots as in int... numbers, lets a method accept any number of arguments, including none. Since Java 5 it is how printf, String.format, List.of and Arrays.asList accept their arguments. Underneath it is just an array, created by the compiler at every call, and that explains all of its rules and traps. This page shows what javac generates, the rules for declaring and overloading, the null and array ambiguity, heap pollution with generics, and the cost.
Contents
Varargs is an array in disguise
Inside the method, a varargs parameter int... numbersint[]sum(7, 8, 9)sum(new int[] {7, 8, 9})
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.spi.ToolProvider;
// Compiles a varargs method and a call to it, then shows what javac generated
public class VarargsBytecode {
static final String SOURCE = """
class Calls {
static int sum(int... numbers) {
return numbers.length;
}
static int call() {
return sum(7, 8, 9);
}
}
""";
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("varargs");
Files.writeString(dir.resolve("Calls.java"), SOURCE);
run("javac", "-d", dir.toString(), dir.resolve("Calls.java").toString());
String out = run("javap", "-c", "-v", "-cp", dir.toString(), "Calls");
out.lines()
.map(String::strip)
.filter(l -> l.startsWith("static int sum") || l.startsWith("flags: (0x0088)")
|| l.matches("\\d+: (iconst|bipush|newarray|iastore|invokestatic).*"))
.map(l -> l.replaceAll("\\s+//.*", ""))
.forEach(System.out::println);
}
static String run(String tool, String... args) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ToolProvider.findFirst(tool).orElseThrow().run(pw, pw, args);
pw.flush();
return sw.toString();
}
}
Output:
static int sum(int...);
flags: (0x0088) ACC_STATIC, ACC_VARARGS
0: iconst_3
1: newarray int
4: iconst_0
5: bipush 7
7: iastore
9: iconst_1
10: bipush 8
12: iastore
14: iconst_2
15: bipush 9
17: iastore
18: invokestatic #7
- The method itself is a normal method taking
, marked with theint[] flag so that the compiler knows it may collect arguments for it.ACC_VARARGS - The call site creates an array of length 3 (
,iconst_3 ), stores 7, 8 and 9 into it one by one (newarray int ), and then callsiastore . Every call allocates a new array; a call with no arguments allocates an empty one.sum
| Rule | Example |
|---|---|
| Only one per method, and it must be the last parameter | String command(String program, String... options) |
| Zero arguments are allowed | sum()null |
| An existing array can be passed directly | sum(new int[] {10, 20}) |
| Inside the method it is an array | numbers.lengthnumbers[0] |
| Fixed-arity overloads are preferred | which(int, int)which(int...) |
Declaring and calling varargs methods
The program calls a summax
import java.util.Arrays;
public class VarargsBasics {
// int... numbers is an int[] inside the method
static int sum(int... numbers) {
System.out.print(" received " + numbers.length + " args " + Arrays.toString(numbers));
int total = 0;
for (int n : numbers) {
total += n;
}
System.out.println(" -> " + total);
return total;
}
// Fixed parameters first; the varargs parameter must be last
static String command(String program, String... options) {
return options.length == 0 ? program : program + " " + String.join(" ", options);
}
// Requiring at least one argument: make the first one a normal parameter
static int max(int first, int... rest) {
int best = first;
for (int n : rest) {
best = Math.max(best, n);
}
return best;
}
public static void main(String[] args) {
sum();
sum(5);
sum(1, 2, 3);
sum(new int[] {10, 20}); // an existing array is passed as-is
System.out.println(command("ls"));
System.out.println(command("ls", "-l", "-a"));
System.out.println("max(4, 9, 2) = " + max(4, 9, 2));
// max(); would not compile: first is required
// JDK examples
System.out.println(String.format("%s-%d", "id", 7));
System.out.println(Arrays.asList("a", "b", "c"));
}
}
Output:
received 0 args [] -> 0
received 1 args [5] -> 5
received 3 args [1, 2, 3] -> 6
received 2 args [10, 20] -> 30
ls
ls -l -a
max(4, 9, 2) = 9
id-7
[a, b, c]
- With no arguments,
received an empty array, so the loop simply did not run and the result was 0. Varargs methods never need asum check for the no-argument case.null - Passing
passed that array as it is, without wrapping it in another array.new int[] {10, 20} has a fixed first parameter and optional ones after it. The varargs parameter must be last, so there is never doubt about which arguments belong to it.command makes at least one argument mandatory, somax(int first, int... rest) is a compile error rather than a run-time check for an empty array.max()
Traps: null, arrays and overloading
Because the parameter is an array, some calls are ambiguous: is a nullString[]Object...
import java.util.ArrayList;
import java.util.List;
public class VarargsTraps {
static int count(Object... items) {
return items == null ? -1 : items.length;
}
static String which(int a, int b) {
return "two ints";
}
static String which(int... a) {
return "varargs";
}
// Generic varargs create a generic array; @SafeVarargs promises not to misuse it
@SafeVarargs
static <T> List<T> listOf(T... items) {
List<T> list = new ArrayList<>();
for (T t : items) {
list.add(t);
}
return list;
}
public static void main(String[] args) {
// 1. null and arrays are ambiguous with Object...
System.out.println("count() = " + count());
System.out.println("count((Object) null) = " + count((Object) null));
System.out.println("count((Object[]) null) = " + count((Object[]) null));
String[] words = {"a", "b", "c"};
System.out.println("count(words) = " + count((Object[]) words));
System.out.println("count((Object) words) = " + count((Object) words));
// 2. Overloading: the fixed-arity method wins
System.out.println("which(1, 2) -> " + which(1, 2));
System.out.println("which(1, 2, 3) -> " + which(1, 2, 3));
// 3. Each call allocates a new array
System.out.println("listOf: " + listOf("x", "y"));
}
}
Output:
count() = 0
count((Object) null) = 1
count((Object[]) null) = -1
count(words) = 3
count((Object) words) = 1
which(1, 2) -> two ints
which(1, 2, 3) -> varargs
listOf: [x, y]
is one argument whose value iscount((Object) null) , so the array has length 1.null passescount((Object[]) null) as the array itself, so the method receivednull and returned -1. A plainnull compiles with a warning, and means the second.count(null)- A
is also anString[] , soObject[] passed it as the argument array and counted 3. Casting it tocount(words) made it a single argument, so the count was 1.Object in reflection is affected by exactly this.Method.invoke(target, args) chose the two-int method. Java resolves overloads in phases and considers varargs methods only if no other method fits, so a varargs overload is always the last resort.which(1, 2)
Generic varargs, heap pollution and @SafeVarargs
A generic varargs parameter T...TT
public class HeapPollution {
// UNSAFE: returns the varargs array itself, whose runtime type is Object[]
@SuppressWarnings("unchecked")
static <T> T[] toArray(T... items) {
return items;
}
// Calls toArray from generic code: T is erased, so javac creates an Object[]
@SuppressWarnings("unchecked") // javac: "unchecked generic array creation"
static <T> T[] pickTwo(T a, T b, T c) {
return toArray(a, b);
}
// SAFE: only reads the array, so @SafeVarargs is an honest promise
@SafeVarargs
static <T> T first(T... items) {
return items[0];
}
public static void main(String[] args) {
String[] direct = toArray("x", "y"); // called with known types: a String[]
System.out.println("direct call: " + direct.getClass().getSimpleName());
System.out.println("first: " + first("a", "b"));
try {
String[] picked = pickTwo("a", "b", "c"); // the array is really an Object[]
System.out.println(picked.length);
} catch (ClassCastException e) {
System.out.println("pickTwo: ClassCastException: Object[] cannot be cast to String[]");
}
}
}
Output:
direct call: String[]
first: a
pickTwo: ClassCastException: Object[] cannot be cast to String[]
- Called with strings,
got a realtoArray("x", "y") , because the call site knewString[] wasT .String - Inside the generic
,pickTwo is erased, so the compiler created anT to callObject[] . That array was returned totoArray as a "main ", and the cast inserted there failed withString[] , far from the code that caused it. A variable of a generic type holding an object of the wrong type is called heap pollution.ClassCastException - javac warns about this. On the declaration: "Possible heap pollution from parameterized vararg type T". At generic call sites: "unchecked generic array creation for varargs parameter". The program suppresses both to show the failure.
(Java 7) is a promise that the method only reads its varargs array and never stores into it or lets it escape.@SafeVarargs keeps that promise. The annotation silences the warnings for all callers. It is allowed on static, final and private methods and on constructors, so that no override can break the promise.first andList.of(E...) use it.Arrays.asList
Aliasing and the cost of the array
The program shows that a method can change the caller's array when an array is passed in, counts the List.of
import java.util.Arrays;
import java.util.List;
public class AliasingAndCost {
static void normalize(double... values) {
double max = Arrays.stream(values).max().orElse(1);
for (int i = 0; i < values.length; i++) {
values[i] /= max; // changes the array it was given
}
}
static int varargsSum(int... n) {
int s = 0;
for (int x : n) {
s += x;
}
return s;
}
static int fixedSum(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
// Passing an array: the method works on the caller's array
double[] readings = {2.0, 4.0, 8.0};
normalize(readings);
System.out.println("caller's array after normalize(readings): "
+ Arrays.toString(readings));
normalize(2.0, 4.0, 8.0); // a fresh array, thrown away afterwards
System.out.println("normalize(2.0, 4.0, 8.0) changed only a temporary array");
// Why List.of has fixed-argument overloads for up to 10 elements
long overloads = Arrays.stream(List.class.getMethods())
.filter(m -> m.getName().equals("of")).count();
System.out.println("List.of overloads: " + overloads + " (0 to 10 elements, plus varargs)");
// A rough cost comparison, best of 3 runs
int n = 100000000;
long bestVar = Long.MAX_VALUE;
long bestFixed = Long.MAX_VALUE;
long check = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
for (int i = 0; i < n; i++) {
check += varargsSum(i, 1, 2);
}
long t1 = System.nanoTime();
for (int i = 0; i < n; i++) {
check -= fixedSum(i, 1, 2);
}
long t2 = System.nanoTime();
bestVar = Math.min(bestVar, t1 - t0);
bestFixed = Math.min(bestFixed, t2 - t1);
}
System.out.printf("100M calls: varargs %d ms, fixed %d ms (check %d)%n",
bestVar / 1000000, bestFixed / 1000000, check);
}
}
Output:
caller's array after normalize(readings): [0.25, 0.5, 1.0]
normalize(2.0, 4.0, 8.0) changed only a temporary array
List.of overloads: 12 (0 to 10 elements, plus varargs)
100M calls: varargs 28 ms, fixed 26 ms (check 0)
divided the caller's own array in place, because the array was passed, not copied. With separate arguments, the method changed a temporary array that nobody could see. A varargs method should not modify its array unless that is its documented purpose.normalize(readings) has 12List methods: one for each count from 0 to 10, plus the varargs one. The fixed overloads exist so that the common short calls allocate no varargs array;of does the same.EnumSet.of- In this loop, the varargs calls cost the same as the fixed ones: the JIT compiler inlined
and, through escape analysis, removed the array allocation entirely. When the method is too large to inline, or the array escapes, every call allocates, which matters in very hot code and is why JDK APIs provide fixed-arity overloads.varargsSum
Varargs in JDK APIs and reflection
Many JDK methods take varargs, and the "is an array the argument list or one argument?" question from the traps section appears in real code with them. The program passes arrays to String.formatArrays.asList
import java.lang.reflect.Method;
import java.util.Arrays;
public class VarargsInApis {
public static String join(String... parts) {
return String.join("+", parts);
}
public static void main(String... args) throws Exception { // main can be varargs
// String.format(String, Object...): an Object[] is spread into the arguments
Object[] values = {"Ada", 36};
System.out.println(String.format("%s is %d", values));
// A String[] is also an Object[], so it is spread too
String[] names = {"Ada", "Linus"};
System.out.println(String.format("%s and %s", (Object[]) names));
// Reflection: Method.invoke(Object target, Object... args)
Method m = VarargsInApis.class.getMethod("join", String[].class);
System.out.println("method is varargs: " + m.isVarArgs());
String[] parts = {"a", "b", "c"};
try {
m.invoke(null, (Object[]) parts); // spread: 3 arguments for 1 parameter
} catch (IllegalArgumentException e) {
System.out.println("invoke(null, parts as Object[]): " + e.getMessage());
}
System.out.println("invoke(null, (Object) parts): " + m.invoke(null, (Object) parts));
// Arrays.asList on an array of objects spreads it; on an int[] it does not
System.out.println("Arrays.asList(String[]) size " + Arrays.asList(parts).size()
+ ", Arrays.asList(int[]) size " + Arrays.asList(new int[] {1, 2, 3}).size());
}
}
Output:
Ada is 36
Ada and Linus
method is varargs: true
invoke(null, parts as Object[]): wrong number of arguments: 3 expected: 1
invoke(null, (Object) parts): a+b+c
Arrays.asList(String[]) size 3, Arrays.asList(int[]) size 1
received theString.format(String, Object...) as its argument array, so "Ada" and 36 filled the two placeholders. AObject[] is also anString[] ; the explicitObject[] cast states that the array should be spread and avoids a compiler warning about the ambiguity.(Object[]) is itself a varargs method. Passing theMethod.invoke(Object target, Object... args) as anString[] spread it into three arguments for a method with one parameter: "wrong number of arguments: 3 expected: 1". Casting it toObject[] made it the single argument the method expects. The same applies toObject , and to invoking aConstructor.newInstance method by reflection.main(String[]) can be declared asmain ; the JVM sees no difference, because it is amain(String... args) either way.String[] reports theisVarArgs() flag shown at the top of this page.ACC_VARARGS spreads an array of objects into a list of 3, but anArrays.asList(T...) is not aint[] for any object typeT[] , so the whole array became the single element of a 1-element list.T
Guidelines
| Do | Avoid |
|---|---|
| Use varargs for "zero or more of the same kind" of argument | Varargs for arguments with different meanings |
| Put required arguments before the varargs parameter | Checking length == 0 |
| Add fixed-arity overloads for the common counts in hot code | Overloading two varargs methods with similar types |
Mark read-only generic varargs methods @SafeVarargs | Returning or storing a generic varargs array |
Pass (Object) x(Object[]) x | method(null)Object... |
Varargs arrays behave like any other Arrays.asList(int[])