What do three dots (...) indicate when used as a part of parameters during method definition?
Also, is there any programming term for the symbol of those 3 dots?
I noticed in a code sample:
public void method1 (Animal... animal) {
// Code
}
And this method was called from 2 places. The arguments passed while calling were different in both scenarios though:
Array of objects is passed as an argument to method1(Animal...)
Object of class Animal passed as an argument to method1(Animal...)
So, is it something like, if you are not sure whether you will be passing a single element of an array or the entire array as an argument to the method, you use 3 dots as a part of parameters in the method definition?
Also, please let me know if there is any programming term for the symbol of those 3 dots.
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.
The three dots are known as the spread operator from Typescript (also from ES7). The spread operator return all elements of an array. Like you would write each element separately: let myArr = [1, 2, 3]; return [1, 2, 3]; //is the same as: return [...myArr];
Rest operator. When used within the signature of a function, where the function's arguments should be, either replacing the arguments completely or alongside the function's arguments, the three dots are also called the rest operator.
When three dots (…) is at the end of function parameters, it's "rest parameters" and gathers the rest of the list of arguments into an array. When three dots (…) occurs in a function call or alike, it's called a "spread operator" and expands an array into a list.
It's called varargs.
It means you can pass as many of that type as you want.
It actually translates it into method1(Animal[] a)
and you reference them as a[1]
like you would any other array.
If I have the following
Cat whiskers = new Cat();
Dog rufus = new Dog();
Dolphin flipper = new Dolphin();
method1(whiskers, rufus, flipper); // okay!
method1(rufus); // okay!
method1(); // okay!
method1(flipper,new Parakeet()); // okay!
That means that the method accepts an Array of that type of Objects but, that array is created automatically when you pass several Objects of that type separated by commas.
Keep in mind that there can only be one vararg parameter of a given type in a method signature, and you can't have another argument of the same type in the signature following the vararg (obviously, there would be no way of distinguishing between the two).
It means that zero or more String objects (or an array of them) may be passed as the parameter(s) for that function.
Maybe:
x("foo", "bar");
x("foo", "bar", "baz");
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