Varargs in Java: Syntax, Array Behaviour and Overloading Traps

One Java method can accept zero, one or several arguments. Trace how varargs use arrays, see when mutations affect the caller, and distinguish compilation errors from runtime exceptions.

KnowledgeGate Team

Exam prep & CS education

Updated 6 Dec 20265 min read
Varargs in Java: Syntax, Array Behaviour and Overloading Traps

You need one method that handles sum(4), sum(4, 7, 9) and even sum() without writing a separate declaration for every argument count. Java varargs use ... to make those calls flexible while the method receives an array. A runnable example shows how those calls are packed, and the same rules explain compile-time failures and runtime exceptions.

What int... values means

In static int sum(int... values), int is the element type, ... marks the variable-arity parameter, and values has type int[] inside the method. You may pass zero or more compatible values, or one existing int[]. This does not allow arbitrary mixed types: a String is not an element for int....

A parameter belongs to the declaration; arguments are supplied by the caller. The broader Methods in Java: Syntax, Parameters and Examples guide explains declarations, parameters and return values; varargs add array packing and overload-resolution rules to that foundation.

You can place ordinary parameters before varargs. Declare this method inside a class:

java
static void log(String label, int... values) { }

Then log("marks", 4, 7, 9) supplies the label separately from the integer elements. There can be at most one varargs parameter, and it must be last. This separate declaration is intentionally invalid:

java
static void bad(int... values, String label) { } // Compile error

Trace a complete varargs sum

Varargs packs 4, 7, 9 into int[] values, then the accumulator reaches and returns 20.

Save this complete program as VarargsDemo.java:

java
public class VarargsDemo {
    static int sum(int... values) {
        int total = 0;
        for (int value : values) {
            total += value;
        }
        return total;
    }

    public static void main(String[] args) {
        System.out.println(sum());
        System.out.println(sum(4));
        System.out.println(sum(4, 7, 9));
        System.out.println(sum(new int[]{2, 6}));
    }
}

Compile with javac VarargsDemo.java, then run java VarargsDemo. The output is:

Code
0
4
20
8

For sum(4, 7, 9), Java packs the arguments into an array equivalent to new int[]{4, 7, 9}. Therefore, values.length is 3. The accumulator starts at 0 and changes once per element:

  1. First element: 0 + 4 = 4.

  2. Second element: 4 + 7 = 11.

  3. Third element: 11 + 9 = 20.

The loop finishes, and the method returns 20.

Diagram shows sum(4, 7, 9) packed into int[] values, accumulator steps 0 + 4 = 4, 4 + 7 = 11, 11 + 9 = 20, and sum() returning 0.

For sum(), the supplied array is empty. The loop executes zero times, leaving total at 0. For sum(4), one iteration gives 0 + 4 = 4. The explicitly supplied array in the final call is passed directly: 0 + 2 = 2, followed by 2 + 6 = 8.

An existing array is not automatically copied

Consider this method:

java
static void bumpFirst(int... values) {
    values[0] += 10;
}

Call it with an existing array:

java
int[] scores = {4, 7, 9};
bumpFirst(scores);
System.out.println(scores[0]); // 14

The update is 4 + 10 = 14, so scores becomes {14, 7, 9}. Java passes the reference value by value. The caller's variable and the parameter refer to the same array; Java is not pass-by-reference. Arrays in Java explains indexing and element updates in more detail.

Now pass a single primitive value:

java
int score = 4;
bumpFirst(score);
System.out.println(score); // 4

Only the temporary array's element becomes 14. The local variable score stays 4. Calling bumpFirst() throws ArrayIndexOutOfBoundsException; check values.length before indexing if empty input is valid.

Also, sum(int[]) and sum(int...) cannot coexist as otherwise identical overloads. Both have the same parameter type. Varargs notation changes the calls permitted, not that underlying type.

Why some overloads win and others are ambiguous

Consider this pair independently:

java
static String pick(int x) { return "fixed"; }
static String pick(int... x) { return "varargs"; }

pick(4) returns "fixed". Both pick(4, 7) and pick() return "varargs".

Overload resolution checks applicable matching-arity methods before expanding variable arguments. For pick(4), the single int parameter already matches. For the other two calls, argument packing makes the varargs method applicable.

Do not memorise “non-varargs always wins”. A varargs declaration can itself be called with matching arity when supplied its array type: pick(new int[]{4}) returns "varargs" without packing individual elements.

Now consider a different pair:

java
static String choose(int... x) { return "ints"; }
static String choose(boolean... x) { return "booleans"; }

choose(4) returns "ints", and choose(true) returns "booleans". The element type identifies the applicable method. But this call is intentionally commented out:

java
// choose(); // Compile error: ambiguous

Both declarations accept zero elements, and neither is more specific. The compiler cannot select one. An ambiguous call never reaches runtime, so it cannot produce an output or throw a runtime exception. When designing an API, prefer distinct method names if empty calls would otherwise create this puzzle.

Empty input and null are different contracts

With the original sum method, these calls behave differently:

java
sum();              // Returns 0
sum((int[]) null);  // Throws NullPointerException

An empty array exists and has length 0. A null reference points to no array, so the enhanced loop fails when it tries to access the array. Decide and document whether your method rejects null; varargs syntax does not automatically impose a null policy.

For reference elements, distinguish a null array from an array containing null. Consider this independent method:

java
static int count(String... words) {
    return words.length;
}

Its calls make the distinction explicit:

java
count();                // Returns 0
count((String) null);   // Returns 1
count((String[]) null); // Throws NullPointerException

The String cast supplies one element, whose value is null. The String[] cast supplies the array reference itself as null. Reading the cast is essential before predicting the result.

How an exam or interview can test this

Try these original checks before reading the answers. Classify each as a returned value, a compilation error or a runtime exception.

  1. What happens when the original method receives sum(2, 6)?

  2. Can otherwise identical sum(int[]) and sum(int...) declarations appear together?

  3. Does choose() compile with the isolated integer and boolean overloads above?

The first returns 8: start at 0, add 2 to get 2, then add 6 to get 8. The second is a compilation error because the parameter types are identical. The third is a compilation error because the empty call is ambiguous.

Oracle's Java Language Specification, Java SE 21, §15.12.2, defines phased applicability checks: strict invocation first, loose invocation next, and variable-arity invocation last. This order explains why counting arguments alone is insufficient.

For broader coding preparation after these checks, explore the Coding & DSA courses.

The short version and your next exercise

Varargs provide convenient call syntax over an array parameter. Put that parameter last, handle empty input intentionally, and keep overloads unambiguous. Remember that passing an existing array permits the method to mutate its elements.

Implement static int sumFrom(int start, int... values). Initialise total to start, add each value, and return the result. Run all three checks:

  • sumFrom(10) gives 10, with no additions.

  • sumFrom(10, 4, 7) gives 21: 10 + 4 = 14, then 14 + 7 = 21.

  • sumFrom(-2, 2, 6) gives 6: -2 + 2 = 0, then 0 + 6 = 6.

After completing the exercise, the Java Course is an optional structured next step.