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... numbers is an ordinary int[]. At each call site, the compiler collects the arguments into a new array and passes that. So sum(7, 8, 9) is compiled as sum(new int[] {7, 8, 9}). The program compiles exactly that call and shows the bytecode javac produced.

Java
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:

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 int[], marked with the ACC_VARARGS flag so that the compiler knows it may collect arguments for it.
  • The call site creates an array of length 3 (iconst_3, newarray int), stores 7, 8 and 9 into it one by one (iastore), and then calls sum. Every call allocates a new array; a call with no arguments allocates an empty one.
Rules for varargs parameters
RuleExample
Only one per method, and it must be the last parameterString command(String program, String... options)
Zero arguments are allowedsum() receives an empty array, never null
An existing array can be passed directlysum(new int[] {10, 20})
Inside the method it is an arraynumbers.length, numbers[0]
Fixed-arity overloads are preferredwhich(int, int) beats which(int...) for two arguments

Declaring and calling varargs methods

The program calls a sum method with zero, one and three arguments and with an existing array, builds a command line from a fixed program name and optional flags, and writes a max that requires at least one value.

Java
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:

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, sum received an empty array, so the loop simply did not run and the result was 0. Varargs methods never need a null check for the no-argument case.
  • Passing new int[] {10, 20} passed that array as it is, without wrapping it in another array.
  • command 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.
  • max(int first, int... rest) makes at least one argument mandatory, so max() is a compile error rather than a run-time check for an empty array.

Traps: null, arrays and overloading

Because the parameter is an array, some calls are ambiguous: is a null argument the array itself, or one element? Is a String[] the array of arguments, or a single argument? The program asks a method that counts its Object... arguments, and then calls an overloaded method with two and three arguments.

Java
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:

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]
  • count((Object) null) is one argument whose value is null, so the array has length 1. count((Object[]) null) passes null as the array itself, so the method received null and returned -1. A plain count(null) compiles with a warning, and means the second.
  • A String[] is also an Object[], so count(words) passed it as the argument array and counted 3. Casting it to Object made it a single argument, so the count was 1. Method.invoke(target, args) in reflection is affected by exactly this.
  • which(1, 2) 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.

Generic varargs, heap pollution and @SafeVarargs

A generic varargs parameter T... needs an array of T, which cannot be created because T is erased (see generics). The compiler creates an array of whatever type it knows at the call site. The program returns that array from a method, which is safe when the caller knows the type and fails when the caller is itself generic.

Java
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:

Output
direct call: String[]
first: a
pickTwo: ClassCastException: Object[] cannot be cast to String[]
  • Called with strings, toArray("x", "y") got a real String[], because the call site knew T was String.
  • Inside the generic pickTwo, T is erased, so the compiler created an Object[] to call toArray. That array was returned to main as a "String[]", and the cast inserted there failed with ClassCastException, far from the code that caused it. A variable of a generic type holding an object of the wrong type is called heap pollution.
  • 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.
  • @SafeVarargs (Java 7) is a promise that the method only reads its varargs array and never stores into it or lets it escape. first 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. List.of(E...) and Arrays.asList use it.

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 overloads, and compares 100 million calls to a varargs method with calls to a fixed-argument method. Each timing is the best of 3 runs, a rough comparison.

Java
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:

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)
  • normalize(readings) 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.
  • List has 12 of 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; EnumSet.of does the same.
  • In this loop, the varargs calls cost the same as the fixed ones: the JIT compiler inlined varargsSum 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.

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.format, calls a varargs method through reflection, where getting it wrong produces an exception, and compares Arrays.asList on object and primitive arrays.

Java
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:

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
  • String.format(String, Object...) received the Object[] as its argument array, so "Ada" and 36 filled the two placeholders. A String[] is also an Object[]; the explicit (Object[]) cast states that the array should be spread and avoids a compiler warning about the ambiguity.
  • Method.invoke(Object target, Object... args) is itself a varargs method. Passing the String[] as an Object[] spread it into three arguments for a method with one parameter: "wrong number of arguments: 3 expected: 1". Casting it to Object made it the single argument the method expects. The same applies to Constructor.newInstance, and to invoking a main(String[]) method by reflection.
  • main can be declared as main(String... args); the JVM sees no difference, because it is a String[] either way. isVarArgs() reports the ACC_VARARGS flag shown at the top of this page.
  • Arrays.asList(T...) spreads an array of objects into a list of 3, but an int[] is not a T[] for any object type T, so the whole array became the single element of a 1-element list.

Guidelines

Using varargs well
DoAvoid
Use varargs for "zero or more of the same kind" of argumentVarargs for arguments with different meanings
Put required arguments before the varargs parameterChecking length == 0 at run time when one is required
Add fixed-arity overloads for the common counts in hot codeOverloading two varargs methods with similar types
Mark read-only generic varargs methods @SafeVarargsReturning or storing a generic varargs array
Pass (Object) x or (Object[]) x to make intent explicitmethod(null) on an Object... parameter

Varargs arrays behave like any other array, including the Arrays.asList(int[]) trap described there.