< Prev
Next >



Varargs in Java





In Java, a vararg is a type of variable declared in a method parameters. A method parameter declared as a 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.





class A
{

public void meth(int... a)
{
System.out.println("method called");
}


public static void main(String... ar)
{
A ob= new A();
ob.meth(); 	//Caling meth() with zero argument
ob.meth(1);	//Caling meth() with one argument
ob.meth(1,2,3);	//Caling meth() with multiple arguments
}
}


Output is


method called
method called
method called

Method meth() is created with a varargs parameter of type int and we have successfully called this method with zero, one or multiple arguments.




Reading variable number of values passed to a method with varargs argument.


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

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 length variable of varargs parameter.



Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter




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

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page

Notifications



COMING SOON
-
PYTHON