Java variable number or arguments for a method

user69514 picture user69514 · Feb 25, 2010 · Viewed 199.4k times · Source

Is it possible to declare a method that will allow a variable number of parameters ?

What is the symbolism used in the definition that indicate that the method should allow a variable number of parameters?

Answer: varargs

Answer

BalusC picture BalusC · Feb 25, 2010

That's correct. You can find more about it in the Oracle guide on varargs.

Here's an example:

void foo(String... args) {
    for (String arg : args) {
        System.out.println(arg);
    }
}

which can be called as

foo("foo"); // Single arg.
foo("foo", "bar"); // Multiple args.
foo("foo", "bar", "lol"); // Don't matter how many!
foo(new String[] { "foo", "bar" }); // Arrays are also accepted.
foo(); // And even no args.