Codectionary / Developer documentation / Java

Variable Arguments with Varargs

Accept zero or more arguments of one type without writing a separate overload for every argument count.

What it is and why to use it

A reporting method may need to total two scores today and five tomorrow. A variable-arity parameter, written int... scores, lets callers supply different numbers of int arguments. Inside the method, scores is an ordinary int array, so the same loop handles all argument counts.

How it works

The variable-arity parameter must be last in the parameter list, and a method can have only one. Calling total() supplies an empty array; calling total(4, 6, 8) supplies three values. An existing int[] can also be passed directly. Varargs changes how calls are written, not how array elements are processed.

Common mistakes and limitations

Do not place another parameter after the varargs parameter. Avoid explicitly passing null: that can make the array itself null and cause iteration to fail. Overloading several similar varargs methods can also make calls ambiguous.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

static int total(int... scores) { /* use scores as int[] */ }

Examples

Variable Arguments with Varargs

Complete Main.java example — Java 17 or later, without preview features.

public class Main {
  static int total(int... scores) {
    int sum = 0;
    for (int score : scores) sum += score;
    return sum;
  }

  public static void main(String[] args) {
    System.out.println(total(4, 6, 8));
    System.out.println(total());
  }
}
  1. total receives three numbers in an array for the first call; the enhanced for loop visits each value.
  2. sum starts at zero and += adds each score, producing 18.
  3. The second call has no arguments, so the loop executes zero times and the result stays zero. This is useful for a small aggregation helper.
  4. Expected output: 18 0

Best practices

  • Document what an empty argument list means.
  • Prefer a collection parameter when callers already manage a large collection.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading