articles

Home / DeveloperSection / Articles / Variable Arguments(Varargs ) in Java

Variable Arguments(Varargs ) in Java

Anupam Mishra4759 01-Dec-2015

In Java, the Variable Arguments allows the method to accept zero or multiple arguments. Before, variable arguments either we use overloaded method or take an array as the method parameter.

But it was not considered good because it leads to the maintenance problem. If we don’t know how many arguments we will have to pass in the method .Varargs is the better approach. The Varargs are widely used to that we don’t have to provide overloaded method.

Varargs syntax are as follows:
       Return_type method_name (data_type … varable_name)
      {
        /* write method body */
       }
Varargs are follows basically two rules. These are:
I.     There can be only one variable arguments in the method.i.e.
void Method1 (String … str, int …n)      //  compile time error
void Method1 (String str, int …n)      // successful compile & run

II.    Variable arguments (Varargs) must be the last arguments.i.e. 

  void Method1 (String … str, int n)   // compile time error
void Method1 (String str, int …n)    //successful compile & run

For example, we have working with various primitives types values in methods using Varargs. 

public class Varargs{
static void var(int ... n)
{
System.out.print("var(int ...) : "+"Number of arguments: "+n.length+"  Contents ");
for(int nn:n)
System.out.print(nn+" ");
System.out.println();
}
static void var(boolean ... b1){
System.out.print("var(boolean ...) : "+"Number of arguments: "+b1.length+" Contents ");
for(boolean b:b1)
System.out.print(b+" ");
System.out.println();
}
static void var(String str,int ... n){
System.out.print("var(String str, int… n) : "+"Number of arguments: "+n.length+" Contents ");
for(int n1:n)
System.out.print(n1+" ");
System.out.println();
}
public static void main(String[] args)
{
var(12,3,3);
var("Test",20,30);
var(true,false,true);
}
}

Output:

Var(int …) : Number of arguments: 3 Contents 12 3 3

Var(String str,int … n) : Number of arguments: 2 Contents 20 30

Var(boolean …) : Number of arguments: 3 Contents true false true


 


Updated 09-May-2019

Leave Comment

Comments

Liked By