Memra

Varargs

◈ 4 cards

Variable-length argument lists — syntactic sugar over an array.

Variable-argument methods

Varargs let a method accept any number of same-type arguments — zero, one, or many — without the caller building an array explicitly:

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

sum(1, 2, 3);             // caller passes comma-separated values
sum(new int[]{1, 2, 3}); // or an explicit array — both work
sum();                    // zero args is valid

Inside the method, nums is a plain int[]. The three-dot syntax is purely compiler sugar: it builds the array on the caller's behalf.

Rules: - A varargs parameter must be last in the parameter list. - A method may have at most one varargs parameter. - Overload ambiguity: if multiple overloads each match a call, the compiler reports an error rather than guessing. Varargs overloads are considered last in resolution (after exact match and widening), so a specific overload wins when available.

the callwhat the compiler passesnums inside sumsum(1, 2, 3)new int[]{1, 2, 3}length 3sum(new int[]{1, 2, 3})that array, as-islength 3sum()an empty arraylength 0int... nums is an int[]
The three dots are sugar at the call site only. Whichever form the caller writes, the body of sum receives an int[] — and for a zero-argument call that array is empty, not null.
NORMAL ~/memra/learn/java-from-zero/varargs utf-8 LF