Skip to content

Varargs

Java has introduced a method with a variable number of arguments called 'varargs'. This feature was incorporated with the fifth version of Java. When used, it enables the developer to use a variable-length of arguments without the need to resort to arrays.

In general, the method syntax can be written in this way:

[typ] methodName(type... groupOfArguments)

When you declare the group of arguments it it proceeded by it's type and it remains common for the whole group. It is then followed up by '...' and the given name of the argument 'groupOfArguments'.

Below you will find a simple example of 'varargs' usage, where for the main argument we provide a random number of integer values. We then print them out to the screen.

void printNumbers(int... numbers) {
    for (int i = 0; i < numbers.length; i++) {
        System.out.println(numbers[i]);
    }
}

Here is the example use of the method above:

printNumbers();         // nothing will be printed, correct usage
printNumbers(2);        // 2
printNumbers(3, 125);   // 3 125
printNumbers(1, 2, 3);  // 1 2 3
We also need to remember that the name of the group of arguments should its final element if we wish to use other arguments. It is worth mentioning, that when declaring those arguments we can use only one type of variables (only integers or longs and so on). Below you will find an incorrect use of 'varargs':

void incorrectVarargs(int... numbersGroupA, long... numbersGroupA) { // compilation error
  // main method
}

In the next example we will print out the given arguments with the distinction whether it's a constant argument or a member of the variable arguments group:

void printArgs(int firstArg, int... numbers) {
    System.out.println("Permanent variable: " + firstArg);
    for (int i = 0; i < numbers.length; i++) {
        System.out.println("Variable argument: " + numbers[i]);
    }
}
Example usage:

printArgs();            // Compilation error!
printArgs(3);           // Constant argument: 3
printArgs(1, 2, 3);     // Constant argument: 1
                        // Variable argument: 2
                        // Variable argument: 3

As seen above, the constant argument is a mandatory element of the method execution - otherwise it will lead to compilation errors.