Lion
Lion

Reputation: 19047

An unknown Java syntax

Let's see the following code snippet in Java.

package common;

final public class Main
{
    private static void show(Object... args)    //<--Here it is...
    {
        for(int i=0;i<args.length;i++)
        {
            System.out.println(args[i]);
        }
    }

    public static void main(String[] args)
    {
        show(1, 2, 3, 4, 5, 6, 7, 8, 9);
    }
}

The above code in Java works well and displays numbers starting from 1 to 9 through the only loop on the console. The only question here is the meaning of (Object... args) in the above code.

Upvotes: 0

Views: 109

Answers (2)

Wayne
Wayne

Reputation: 60424

You're using Java's varargs notation, which allows the final argument to be passed as either an array or sequence of arguments (of indeterminate length). In your case, you're passing them as a sequence of args:

show(1, 2, 3, 4, 5, 6, 7, 8, 9);

...but you could also pass them like this:

show(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9});

Without support for this feature, you'd either have needed to accept an array in the method signature (and always passed the inputs in an array) or specified a fixed number of int arguments.

Upvotes: 2

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236150

The three-dot notation is the syntax for variable number of arguments, take a look here.

Upvotes: 6

Related Questions