Learn Java
import com.learnjava.methods.Varargs;

Varargs (Variable-Length Arguments) in Java

@Concept

Varargs let a method accept any number of arguments of a given type — zero, one, or many — using a single parameter marked with three dots: static int sum(int... numbers). Inside the method body, that parameter behaves exactly like a regular int[] array, since that's genuinely what it is under the hood; the three-dot syntax is really just a convenience for the caller, who can pass individual comma-separated values instead of building an array explicitly first.

A method can have ordinary parameters before a varargs parameter, but the varargs parameter must come last, and a method can only have one — the compiler wouldn't otherwise know where one variable-length group ends and the next begins.

@HowItWorks
1

The syntax

Type... name in a parameter list accepts zero or more arguments of that type.

2

It's really an array underneath

Inside the method, the varargs parameter behaves exactly like an ordinary array of that type.

3

Calling with individual values

The caller can list arguments directly, comma-separated, without building an array first.

4

Calling with zero arguments

A varargs parameter can legally receive none at all, resulting in an empty array inside the method.

5

Placement rules

A varargs parameter must be the last one in the list, and a method can have at most one.

@Example
public class VarargsDemo {
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
 
public static void main(String[] args) {
System.out.println(sum(1, 2, 3));
System.out.println(sum());
}
}
Output
6
0
1sum(1, 2, 3) passes three individual values, which arrive inside the method as a 3-element int array.
2The for-each loop adds each of those three elements, giving a total of 6.
3sum() with no arguments at all still compiles, arriving as a valid but empty array.
4The for-each loop over that empty array runs zero times, leaving total at its starting value of 0.
@UseCases
Writing a method that sums, joins, or otherwise combines any number of values
Accepting an optional list of extra arguments without requiring an explicit array from the caller
Understanding why a varargs parameter has to be the last one in a method's parameter list
Recognizing println's own varargs-based overloads for formatted output

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Java yourself — building beats watching.