Do var-args parameters really exist ?

Even if I’ve rarely seen var-args used in real projects, this feature seems useful although its behaviour is disturbing.

If you write this method :

void m (String... vargs) {}

You can use both var-args and arrays as shown below :

m("a", "b", "c");
m(new String[]{"a", "b", "c"});

Why can we swap these both calls without disturbing the JVM ?
Moreover, if you use var-args on the main method, it’ll compile and run fine :

public static void main (String... argv) {}

For me, it’s a proof that in the bytecode these two features are equals, and we’ll check this.
In fact, at compile time, javac replaces var-args by an array like this :

// In source :
void m (String... args) {}

// In bytecode
void m (String[] args) {}

So var-args don’t really exist, it’s just syntaxical sugar for developers !
But … there still is a little problem. Why can’t we use var-args if the prototype uses array ?
For example this code doesn’t compile :

// Method definition
m(String[] args) {}
// Using our method
m("a", "b", "c"); // Compilation fails

The explanation is : when you write a var-args based prototype, and you call your method using var-args (not array), at compile time javac replaces your var-args parameters by an array like in the following snippet.

// Method declaration
m(String... args) {}
// Using our method
m("a", "b", "c");

The real call will be :

// Using our method
m(new String[] {"a", "b", "c"});

Thus var-args really are syntaxical sugar, and this feature is a bit limited.
One more time, thanks to jad !

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s