Skip to content
thesarfo

Concept

Varargs

Passing a variable number of arguments to a Java method, how they're processed as an array, and how they interact with fixed parameters and array arguments.

views 0

Varargs let you pass a varying number of arguments to a method:

public class Test {
public static void main(String[] args) {
m1(); // method call without args
m1(1); // method call with 1 arg
m1(1, 2, 3, 4); // method call with multiple args
}
static void m1(int... a) {
System.out.println(a);
}
}

Varargs are processed as an array — with multiple arguments, you access them with array indexing:

static void m1(int... a) {
System.out.println(a[0]); // prints the first arg; throws ArrayIndexOutOfBoundsException if called with no args
}

Any normal array operation (for-loops, etc.) applies to varargs too.

Varargs can also coexist with fixed parameters — the vararg has to come last:

static void m2(String x, int... y) {
System.out.println(x); // prints the first string arg passed to m2
System.out.println(y.length); // prints the count of the remaining int args, however many were passed
}
m2("abc", 1, 2, 3, 4, 5); // prints "abc" and "5"

You can also pass an array directly as the vararg — but since varargs are already processed as arrays, passing an array of arrays effectively makes it a matrix:

static void m3(int[]... x) {
for (int[] a : x) { // normal looping through a matrix
for (int b : a) {
// ...
}
}
}