Varargs – Variable Length Arguments

When we define a function we may want to allow the user to pass an arbitrary number of arguments into the function.  We can do this with varargs.  A vararg (variable-length argument) is specified with three periods (…) between the type and variable name in the function’s parameter list as shown below.

static void printNames(String ... names) {
    ...
}

This syntax tells the compiler that printNames can be called with zero or more String arguments.  Internally, names is declared as an array of type String that we can access as normal.

static void printNames(String ... names) {
    for (String name : names) {
        System.out.println("Name: " + name);
    }
}

A function can also have other parameters in addition to a variable length argument, however the variable length argument must be the last parameter listed.

static void printNames(String greeting, String ... names) {
    for (String name: names) {
        System.out.println(greeting + " " + name);
    }
}

 

Restriction:  There can be only one variable length argument.

© 2017, Eric. All rights reserved.