Advertisement



< Prev
Next >



Varargs in Java





In Java, varargs is a type of variable that is declared within a method's parameters. It stands for variable arguments. A method parameter declared as the varargs type can be passed a variable number of arguments, i.e. zero or more number of arguments.

A point to remember - A varargs parameter can only be declared within a method's parameters.





A varargs parameter is a variable-length array that holds zero or more values of same type. Hence, just like an array, a varargs parameter also has a length variable which gives the total number of elements contained in it.

//Java - Example of varargs

class A
{
public void meth(int... a)
{
	if(a.length==0)
	System.out.println("number of parameters passed : "+ a.length);

	if(a.length>0)
	{
		System.out.println("number of parameters passed : "+ a.length);

		for(int i=0;i<a.length;i++)	
		System.out.println(a[i]);
	}
}


public static void main(String... ar)
{
	A ob= new A();
	ob.meth();		//calling method() with zero parameter
	ob.meth(1);		//calling method() with one parameter
	ob.meth(1,2,3);  	//calling method() with more than one parameter
}
}


Output is


number of parameters passed : 0
number of parameters passed : 1
1
number of parameters passed : 3
1
2
3

We have called method meth() with zero, one and multiple arguments. These arguments are read using the length variable of varargs parameter.



Please share this article -





< Prev
Next >
< Return Types in Java
Garbage Collector>



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement