String... parameter in Java

98,974

Solution 1

It's called varargs; http://docs.oracle.com/javase/6/docs/technotes/guides/language/varargs.html

It means you can pass an arbitrary number of arguments to the method (even zero).

In the method, the arguments will automatically be put in an array of the specified type, that you use to access the individual arguments.

Solution 2

Yes, that means you can take arbitrary no of Strings as an argument for this method.

For your method:

public void method(String... strs); 

You can call it as:

method(str)
method(str1, str2)
method(str1,str2,str3)

Any no of arguments would work. In other words, it is a replacement for:

 public void method(String[] str); 

Solution 3

It's called an ellipsis and it means the method can take multple Strings as its argument.

See: The Java tutorial on passing arguments on Oracle's site.

Solution 4

See java optional parameters : as of Java 5, Java has support for variable numbers of arguments.

Share:
98,974

Related videos on Youtube

Desh Banks
Author by

Desh Banks

Updated on August 28, 2020

Comments

  • Desh Banks
    Desh Banks over 3 years

    I have to implement an API for a homework assignment, and my instructor has used a notation I am unfamiliar with for one of the methods in the API (javadoc based).

    public void method(String... strs);
    

    What do the '...' mean? It later looks like I'll need to call this same method using a single string actual parameter, as well as multiple string actual parameters...

    Java doesn't have optional arguments (to my knowledge), so I am a little confused here...

  • Brian Roach
    Brian Roach over 12 years
    Uh, no, it doesn't (you're half correct - your first sentence is the problem).
  • Johnydep
    Johnydep over 12 years
    @BrianRoach, Oh yes sorry you are right :)
  • Kennet
    Kennet over 12 years
    Haven't found a max limit of how many arguments varargs can take, but it's definitely more than three
  • Desh Banks
    Desh Banks over 12 years
    Ah, thanks for the quick response. I hadn't seen this before... Very nice.
  • Brian Roach
    Brian Roach over 12 years
    +1 for coming back and fixing it.
  • Desh Banks
    Desh Banks over 12 years
    Thanks for the example. Upon knowing about 'varargs' I've also found that the vararg argument must be the final formal parameter declared in the parameter list of the function using varargs.
  • amphibient
    amphibient over 10 years
    I would just add that this type of function is called variadic: en.wikipedia.org/wiki/Variadic_function