Java Five-Oh #3: Variable Arguments

Variable arguments, or better known as varargs, where also introduced in Java 1.5. The neat thing about varargs is that you can construct a single method that will accept a varied number of arguments. When I am talking about varargs I an not talking about overloading, a single method will accept different number of parameters. Here is how you define a method that makes use of the new vararg feature:

public void print(String... args) {
   for(String s : args)
      out.println(s);
}

In the above sample code I declare vararg method by using the … notation in after the type in the parameter list. This method will accept zero or more string parameters. So the following method calls will be processed by the above function:

print("hello");
print("hello", "hola");

The thing to note is that the args parameter is just an array that is why I was able to use the for/in loop construct. I statically imported java.lang.System.out to make it available locally in the method implementation.