jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Overloading and var args Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Overloading and var args" Watch "Overloading and var args" New topic

Overloading and var args

Gilles Marceau
Ranch Hand

Joined: Feb 17, 2007
Posts: 78

the following code doesn't compile, and i wonder why :

class TestVarArg {
public void doStuff(int[] args) {

public void doStuff(int... args) {


I tough that overloading is allowed if the method argument list is different, and that's the case in this example.
But it doesn't compile, so it seems that, behind the scene, the var
arg is an array (which makes sense, as "args" in doStuff(int... args)
method body is handled as an array).

Does anyone have a clue about this ?

SCJP 1.5<br />SCJD 1.6<br />SCBCD in progress...
satishkumar janakiraman
Ranch Hand

Joined: May 03, 2004
Posts: 334

What compilation errors did you get ? Post your error. I do not see any mistake in your code. It is perfectly correct if the methods are overloaded. For eg doStuff(int[] args) and doStuff(int args)

bye for now
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Hi Giles,

Welcome to JavaRanch!

The code doesn't compile because the two method signatures are the same -- they're two different ways of making the identical declaration. A final argument using the varargs notation is actually compiled into an array argument. One interesting consequence of this is that you can call a method declared using array argument syntax by using the varargs syntax -- for example

List<String> list = Arrays.asList("one", "two", "three");

works just fine.

[Jess in Action][AskingGoodQuestions]
Gilles Marceau
Ranch Hand

Joined: Feb 17, 2007
Posts: 78
Thank you for your answer, i am now a bit more educated about the var args feature.
Remko Strating
Ranch Hand

Joined: Dec 28, 2006
Posts: 893
I think this code will not compile, because there are duplicate methods defined

With the VarArgs there could be used a Array of integers of which the size is not known. This could be 0 to many.

The other method defines a Array of integers.

So the compiler doesn't know which method to choose.

Remko (My website)
SCJP 1.5, SCWCD 1.4, SCDJWS 1.4, SCBCD 1.5, ITIL(Manager), Prince2(Practitioner), Reading/ gaining experience for SCEA,
I agree. Here's the link: http://aspose.com/file-tools
subject: Overloading and var args
It's not a secret anymore!