Friday, 13 July 2012

Varargs in java (Passing variable no of arguments in java program)

After J2SE 5.0 java supports passing of variable arguments in a method that u don't need to fix the no of arguments at the time of defining the method .
Compiler automatically converts the arguments in the form of array so u can access all the arguments at run time.





Example:-


public class Varargs
{

    public static void main(String[] args)
    {

        Varargs var = new Varargs();

        var.show("Ankit", "Singh", "Katiyar");

        var.show("facebook.com\"", "ankitkatiyar91");

    }

    public void show(String... arg)

    {

        for (int i = 0; i < arg.length; i++)

        {

            System.out.println(arg[i]);

        }

    }

}



Note:- it   works only it version J2SE 5.0 or above.

You can use any data type for variable arguments.

Example:-

package javaTest;

public class Varargs {

public static void main(String[] args) {
// TODO Auto-generated method stub
Varargs var=new Varargs();
var.show(1,2,3);
var.show(9,7);

}
public void show(int... arg)
{
for(int i=0;i<arg.length;i++) 
{
System.out.println(arg[i]);
}
}

}

Rules :-
* For any method it must be the last argument.

No comments:

Post a Comment