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

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

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.
The compiler automatically converts the arguments in the form of an array so u can access all the arguments at runtime.


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 for version J2SE 5.0 or above.
You can use any data type for variable arguments.
Example:-

 

public class Varargs {
 
	public static void main(String[] args) {

		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]);
		}
	}
}
Restriction: For any method, it must be the last argument.
Explore more here

Leave a Reply

Your email address will not be published. Required fields are marked *