19

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
  • 72,790
  • 10
  • 128
  • 154
Desh Banks
  • 293
  • 1
  • 2
  • 10

4 Answers4

35

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.

dagge
  • 1,095
  • 8
  • 13
6

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.

Brian Roach
  • 72,790
  • 10
  • 128
  • 154
5

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); 
Johnydep
  • 5,301
  • 19
  • 52
  • 70
1

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

Community
  • 1
  • 1
Borealid
  • 86,367
  • 8
  • 101
  • 120