Java main methods with "..." arrays? [duplicate]
Asked Answered
J

4

6

Possible Duplicate:
What is the ellipsis (…) for in this method signature?
java: how can i create a function that supports any number of parameters?

well i'm trying to figure out some examples and I found this kind of array definition for arguments in the main method. What's so special about this "..." and what's the difference between a normal String[] args?

Thanks

Juratory answered 3/5, 2012 at 1:20 Comment(7)
You probably mean varargs: #4216198Valenti
See this post for more info on how elipsis work in Java.Kymric
@Adam, how on earth is "what have you tried" relevant to a question about the meaning of a specific piece of syntax? (i mean, i think this question should be closed as a dup, but "what have you tried" seems totally irrelevant)Pleader
@KirkWoll Follow the link and read the section starting with "Try taking a few minutes to run through these points:" The site does far more than just tell you to "try it yourself"; it gives some very good advice for asking effective questions.Citronellal
@Adam, I see your point, but in that case, the domain name is particularly unhelpful. Better would be along the lines of Jon Skeet's "Writing the perfect question". No ambiguity and no confusion. But I concede this isn't your problem. :)Pleader
Thanks for the link -- it'll come in handy.Citronellal
#8757448Aguayo
O
7

That's a notation from Java 5 for variable length argument lists. It is roughly equivalent to a String array, but lets you pass individual parameters that are combined into an array automatically.

void mymethod(String... a) {
    for (String s : a) {
        ...
    }
}

mymethod("quick", "brown", "fox");

This makes sense only when you plan to call a method from your program, so I do not see why it would be desirable to use this syntax for your main(). It will work, however.

Obloquy answered 3/5, 2012 at 1:25 Comment(0)
K
3

The elipsis (...) are varargs. They are used when you want to create a method with any number of arguments. Oracle explains how varargs work in detail here.

Kymric answered 3/5, 2012 at 1:27 Comment(0)
I
2

This is called varargs which means any number of arguments can be passed of that type (String).

1.it should be in final position

2.It will be processed as an array

Intertwine answered 3/5, 2012 at 2:20 Comment(0)
K
1

... is used for varargs.

For example

public void myMethod(Object... params) { }

The params variable is optional and is treated as a nullable array of Objects.

Kunzite answered 3/5, 2012 at 3:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.