Video in progress

Strong Junior ☕ Core Java

How does varargs (String... args) work, and what traps does it have?

A varargs parameter is an ordinary array inside the method, and the caller can pass 0 or more arguments. The traps: an array is created on every call, passing null is confusing, and generic varargs gives a heap pollution warning.

📖 Answer

static int sum(int... nums) {
    int s = 0;
    for (int n : nums) s += n;
    return s;
}

sum();            // nums = []
sum(1, 2, 3);
sum(new int[]{4, 5});

The rules:

  • there can be only one varargs parameter, and it has to be the last one;
  • it gets confusing together with overloads: with log(String msg) and log(String... parts), log("x") picks the first one.

The traps:

static void print(String... s) { System.out.println(s.length); }
print(null);            // NPE: s itself, the array, is null
print((String) null);   // 1: an array with a single null element

Performance: in methods that are called very often, an array is created each time. That's why APIs like List.of and SLF4J provide separate overloads for 0, 1, 2 and 3 arguments.

With generic varargs (<T> void addAll(T... items)), the compiler warns about "possible heap pollution". If the method doesn't let the array escape and doesn't write into it, you can add @SafeVarargs.