Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do 3 dots next to a parameter type mean in Java?

What do the 3 dots following String in the following method mean?

public void myMethod(String... strings){     // method body } 
like image 281
Vikram Avatar asked Jul 01 '10 14:07

Vikram


People also ask

What is the three dots in parameter Java?

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.

What does three dots mean in coding?

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

What do dots mean in Java?

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.

What do ellipses mean in Java?

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.


2 Answers

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.

like image 83
kiswa Avatar answered Sep 17 '22 12:09

kiswa


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.

like image 41
Cristian Avatar answered Sep 20 '22 12:09

Cristian