views:

323

answers:

3

I've seen an example of it before, but I've never really found any good reference material dealing with it. I know it's possible to pass in several parameters, ints for example, by defining the method as

public void aMethod(int...a)

But I don't know any more about it than that. I've seen an example, and it returned the average of the ints passed.
Is this an out-dated way of passing parameters? Is it even acceptable to use this? What exactly is the syntax like when doing this? (Some reference material would be great)

+11  A: 

It's called varargs (from the C syntax). See Sun's varargs guide for an overview and this JDC Tech Tip for usage. It is not out-dated; it was put in as a feature request since previously you were forced to create an array or list, which was really ugly for supporting something like C's printf.

public void myMethod(String... args) {
    for (String aString:args) {
        System.out.println(aString);
    }
}
Travis Jensen
As to when to use it, varargs does come with a performance penalty. So only use it when you really have to use it. I've encountered precious little problems in java where I thought 'man, I could really use varargs here' (only printf comes to mind)
wds
A: 

You are going to have to pass a list of ints to the method to do this, something like this:

public void aMethod(int[] list)

or this:

public void aMethod(ArrayList<int> list)

It would be nice if Java had something like C#'s params keyword but it doesn't.

Andrew Hare
The whole point of the "varargs" notation is that you DON'T have to pass an explicit array or list.
joel.neely
I am not much of a Java guy so I had no idea this existed! Good to know!
Andrew Hare
-1 : for Java 5 and later this is incorrect.
Stephen C
A: 

How about if you wanted to pass a list of parameters from different types. Can you do that. For example, a use of printf goes like this

printf("%d... %f... %c... %s", intVar, floatVar, charVar, stringVar);

Is there a way to do that in java???

Gianpaolo
The String.format() method does exactly this. It just declares an Object... argument though.http://java.sun.com/javase/6/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)
David Winslow
This "answer" is a question, not an answer.
Stephen C