Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String... parameter in Java [duplicate]

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...

like image 732
Desh Banks Avatar asked Jan 28 '12 21:01

Desh Banks


People also ask

How do you duplicate a string in Java?

repeated = new String(new char[n]). replace("\0", s);

How do you prevent duplicates in string?

We can remove the duplicate characters from a string by using the simple for loop, sorting, hashing, and IndexOf() method. So, there can be more than one way for removing duplicates. By using the simple for loop. By using the sorting algorithm.


3 Answers

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.

like image 80
dagge Avatar answered Oct 18 '22 20:10

dagge


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); 
like image 34
Johnydep Avatar answered Oct 18 '22 18:10

Johnydep


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.

like image 6
Brian Roach Avatar answered Oct 18 '22 20:10

Brian Roach