What do three dots (...) indicate when used as a part of parameters during method definition?

16,054

Solution 1

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!

Solution 2

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

Solution 3

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");
Share:
16,054

Related videos on Youtube

Vikram
Author by

Vikram

Love to code!!! My love: C, C#, Java, ASP.NET, Microsoft Dynamics CRM etc.

Updated on September 15, 2022

Comments

  • Vikram
    Vikram over 1 year

    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:

    1. Array of objects is passed as an argument to method1(Animal...)

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