Varargs (introduced in Java SE 5) allows you to pass 0, 1, or more params to a method's vararg param. This reduces the need for overloading methods that do the similar things. For example,
package javahowto;
import org.apache.commons.lang.StringUtils;
public class HelloWorld {
public static void main(String[] args) {
hello();
hello("World");
hello("Santa", "Bye");
final String[] names = {"John", "Joe"};
hello(names);
}
public static void hello(String... names) {
final String defaultName = "Duke";
String msg = "Hello, ";
msg += ((names.length == 0) ? defaultName : StringUtils.join(names, ", "));
System.out.println(msg);
}
}
org.apache.commons.lang.StringUtils
is in
commons-lang-2.4.jar
. Running this example gives the following output:
Hello, Duke
Hello, World
Hello, Santa, Bye
Hello, John, Joe
BUILD SUCCESSFUL (total time: 0 seconds)