What do the 3 dots following String
in the following method mean?
public void myMethod(String... strings){ // method body }
The "Three Dots" in java is called the Variable Arguments or varargs. It allows the method to accept zero or multiple arguments. Varargs are very helpful if you don't know how many arguments you will have to pass in the method.
(three dots in JavaScript) is called the Spread Syntax or Spread Operator. This allows an iterable such as an array expression or string to be expanded or an object expression to be expanded wherever placed.
In Java language, the dot operator ( . ) symbolizes the element or operator that works over the syntax. It is often known as a separator, dot, and period. Simply the dot operator acts as an access provider for objects and classes.
notation is actually borrowed from mathematics, and it means "...and so on". As for its use in Java, it stands for varargs , meaning that any number of arguments can be added to the method call.
It means that zero or more String objects (or a single array of them) may be passed as the argument(s) for that method.
See the "Arbitrary Number of Arguments" section here: http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html#varargs
In your example, you could call it as any of the following:
myMethod(); // Likely useless, but possible myMethod("one", "two", "three"); myMethod("solo"); myMethod(new String[]{"a", "b", "c"});
Important Note: The argument(s) passed in this way is always an array - even if there's just one. Make sure you treat it that way in the method body.
Important Note 2: The argument that gets the ...
must be the last in the method signature. So, myMethod(int i, String... strings)
is okay, but myMethod(String... strings, int i)
is not okay.
Thanks to Vash for the clarifications in his comment.
That feature is called varargs, and it's a feature introduced in Java 5. It means that function can receive multiple String
arguments:
myMethod("foo", "bar"); myMethod("foo", "bar", "baz"); myMethod(new String[]{"foo", "var", "baz"}); // you can even pass an array
Then, you can use the String
var as an array:
public void myMethod(String... strings){ for(String whatever : strings){ // do what ever you want } // the code above is equivalent to for( int i = 0; i < strings.length; i++){ // classical for. In this case you use strings[i] } }
This answer borrows heavily from kiswa's and Lorenzo's... and also from Graphain's comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With