Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing several parameters as a single parameter in Java

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)

like image 604
Retsam Avatar asked Sep 27 '26 05:09

Retsam


1 Answers

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);
    }
}
like image 116
Travis Jensen Avatar answered Sep 28 '26 19:09

Travis Jensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!