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

Variable Arguments(Varargs ) in Java

Java Java  J2EE 
0 Comment(s)
 1095  View(s)
Rate this:

Variable Arguments(Varargs) in Java       

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+" ");



static void var(boolean ... b1){

System.out.print("var(boolean ...) : "+"Number of arguments: "+b1.length+" Contents ");

for(boolean b:b1)

System.out.print(b+" ");



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+" ");



public static void main(String[] args)









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


Don't want to miss updates? Please click the below button!

Follow MindStick