Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading using varargs in Java

Tags:

java

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?

like image 507
Lion Avatar asked Jan 25 '26 07:01

Lion


1 Answers

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.

like image 96
Cameron Skinner Avatar answered Jan 27 '26 21:01

Cameron Skinner