3

The following code in Java uses varargs to overload methods.

final public class Main
{
    private void show(int []a)
    {
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+"\t");
        }
    }

    private void show(Object...a)
    {
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+"\t");
        }

        System.out.println("\nvarargs called");
    }

    public static void main(String... args)
    {
        int[]temp=new int[]{1,2,3,4};            

        Main main=new Main();
        main.show(temp);
        main.show();         //<-- How is this possible?
    }
}

The output of the above code is as follows.

1        2        3        4

varargs called

The last line main.show(); within the main() method invokes the show(Object...a){} method which has a varargs formal parameter. How can this statement main.show(); invoke that method which has no actual arguments?

Lion
  • 18,729
  • 22
  • 80
  • 110

3 Answers3

3

main.show() invokes the show(Object... a) method and passes a zero-length array.

Varargs allows you to have zero or more arguments, which is why it is legal to call it with main.show().

Incidentally, I'd recommend that you don't embed \n in your System.out.println statements - the ln bit in println prints a newline for you that will be appropriate for the system you're running on. \n isn't portable.

Cameron Skinner
  • 51,692
  • 2
  • 65
  • 86
1

The varargs syntax basically lets you specify that there are possible parameters, right? They can be there, or cannot be there. That's the purpose of the three dots. When you call the method, you can call it with or without those parameters. This was done to avoid having to pass arrays to the methods. For example, you can write:

main.show(1, 2, 3, 4);

That will also work, because the numbers will become objects in wrapper classes. If you're still confused, take a look at this: http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html or this: When do you use varargs in Java?

Community
  • 1
  • 1
eboix
  • 5,113
  • 1
  • 27
  • 38
1

The main.show() call takes NO arguments, which is perfectly valid for matching the show(Object...a) method.

Gabriel Belingueres
  • 2,945
  • 1
  • 24
  • 32