Friday, August 10, 2007

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", "again", "world!");

public static void myMethod(Object ... args) {
System.out.println("You have passed in " + args.length + " arguments ");
for (Object o : args) {
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

You have passed in 3 arguments

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.

If you like reading this, you may also enjoy:


Archimedes Trajano said...

I think the best use of these varargs that are not part of the JDK e.g. MessageFormat.format(...). Would be in "plumbing" code that you may write that involves passing method paramters across layers as in my EJB Service Locator Pattern.

Another useful place for this would be in System.out.println("abc", "def", someOtherVariable, 1).

But I think they should be avoided when the parameter should have been a List in the first place.

Javin @ java OutOfMemoryError said...

Fantastic article Vincent,vararg is very interesting feature but still under utilized. you know even main method is written using varargs. by the way I also blogged my experience as variable arguments in java let me know how do you find it

Post a Comment