Passing variable length arguments to a Java Method
It is not well known fact that Java can actually handle variable length arguments passed to its method calls. This is achieved by using “…” operator in argument signature of your method declaration, commonly used when certain arguments to the method are optional. Here’s a simple code example to illustrate its usage:
/** Testing variable arguments passing. */
public class Varargs {
public static void main(String args[]) {
myMethod("Hello");
System.out.println();
myMethod("Hello", "again", "world!");
}
public static void myMethod(Object ... args) {
System.out.println("You have passed in " + args.length + " arguments ");
for (Object o : args) {
System.out.println(o);
}
}
}
As you can see, I’ve only declared 1 method called 'myMethod'
, and
have passed an arbitary number of arguments to it, which would have in
the past generated a compiler error telling me that the method
signatures I’ve used are not present. But in this case (with Java 1.5
and above), it compiles and produces the following output:
You have passed in 1 arguments
Hello
You have passed in 3 arguments
Hello
again
world!
The “…” operator does require you must have at least 1 or more
arguments, but while you can pass a null
to it, the compiler will
generate some output to warn you to be explicit in your variable
typing.
Internally, the number of arguments is actually statically determined by
'javac'
compiler, and converted to an object array for processing, so
there are limitations in the sense that it is not truly dynamic, but
just a compilation convenience method that can save you from writing
multiple method signatures for different permutations of the same method
call.