Varargs in Java β€” Variable Number of Arguments

Varargs (variable arguments) let a method accept zero or more values of the same type as if they were individual arguments. The ... syntax (Java 5+) is just sugar for a final array parameter.

Syntax

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

sum();                    // 0 β€” nums is an empty array, not null
sum(1);                   // 1
sum(1, 2, 3);             // 6
sum(new int[]{1, 2, 3});   // 6 β€” passing an array works too

Rules

  • Must be the last parameter.
  • Only one varargs per method.
  • Inside the method, nums is an ordinary array.

JDK examples

String.format("%s is %d years old", name, age);
List.of("a", "b", "c");
Arrays.asList(1, 2, 3);
String.join(", ", "a", "b", "c");
Paths.get("src", "main", "java");

Generic varargs β€” @SafeVarargs

@SafeVarargs                                     // promises no heap pollution
public static <T> List<T> listOf(T... values) {
    return List.of(values);
}

Without the annotation the compiler warns about unchecked generic array creation. Add @SafeVarargs only if the method doesn't write into the varargs array in an unsafe way.

Ambiguous overloads

void log(String msg)            { ... }
void log(String... args)         { ... }

log("hello");                    // calls log(String) β€” exact match wins over varargs
log("hello", "world");           // calls log(String...) β€” only match

Common mistakes

  • Passing null β€” sum(null) passes a single null, not an empty array. You get a NullPointerException on iteration.
  • Using varargs where an array would be clearer β€” if 99% of callers have an array already, save them the new int[]{...} and accept an array.
  • Performance-sensitive hot paths β€” each call allocates an array. For microbenchmarks, fixed-arity overloads are faster.

Related

Pillar: Java methods. See also parameters, overloading.