Varargs

Varargs — variable-length argument lists, added in Java 5 — let a method accept any number of arguments of the same type. Declared with ... (ellipsis) after the parameter type. Inside the method, the parameter is treated as an array.

Example

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

sum();              // 0
sum(1);             // 1
sum(1, 2, 3, 4, 5); // 15
sum(new int[]{1, 2, 3}); // 6 — can pass an array directly

Rules

  • Varargs must be the last parameter.
  • A method can have only one varargs parameter.
  • Inside the method, varargs behaves like an array.

Built-in varargs methods

System.out.printf("%s is %d%n", name, age);    // printf is varargs
List<String> list = Arrays.asList("a", "b", "c");
List<Integer> ints = List.of(1, 2, 3, 4);       // Java 9+

Gotcha: generics and varargs

Mixing generics with varargs can cause "unchecked" warnings due to array / generic interaction. Annotate safe cases with @SafeVarargs:

@SafeVarargs
public static <T> List<T> listOf(T... items) { ... }

See the full varargs tutorial.