Java method with unlimited arguments

Franz Kafka picture Franz Kafka · Aug 30, 2011 · Viewed 65.6k times · Source

The spring framework uses methods where you can pass as many arguments as you like.

I would like to write a function that can also take an unlimited amount of data. How is this feature called so that I can read about it. Or how can I define it?

Thanks so much.

Answer

Bozho picture Bozho · Aug 30, 2011

It's called varargs.

It allows a method to take any number of arguments. They are accessible as an array in the method:

public void foo(String... args) {
    for (String arg : args) {
      // do smth with arg.
     }
}

This is syntactic sugar. The compiler hides the array creation, so instead of

 bar.foo(new String[] {"1", "2", "3"});

you write

 bar.foo("1", "2", "3");