Java Varargs

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Variable Argument (Varargs):

The varrags allows the method to accept zero or muliple arguments. Before varargs 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 argument we will have to pass in the method, varargs is the better approach.

Advantage of Varargs:

We don't have to provide overloaded methods so less code.


Syntax of varargs:

The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:

  1. return_type method_name(data_type... variableName){}  

Simple Example of Varargs in java:

  1. class VarargsExample1{  
  2.    
  3.  static void display(String... values){  
  4.   System.out.println("display method invoked ");  
  5.  }  
  6.   
  7.  public static void main(String args[]){  
  8.   
  9.  display();//zero argument   
  10.  display("my","name","is","varargs");//four arguments  
  11.  }   
  12. }  
  13.       

Test it Now

Output:display method invoked
       display method invoked

Another Program of Varargs in java:

  1. class VarargsExample2{  
  2.    
  3.  static void display(String... values){  
  4.   System.out.println("display method invoked ");  
  5.   for(String s:values){  
  6.    System.out.println(s);  
  7.   }  
  8.  }  
  9.   
  10.  public static void main(String args[]){  
  11.   
  12.  display();//zero argument   
  13.  display("hello");//one argument   
  14.  display("my","name","is","varargs");//four arguments  
  15.  }   
  16. }  
  17.       

Test it Now

Output:display method invoked
       display method invoked
       hello
       display method invoked
       my
       name
       is 
       varargs

Rules for varargs:

While using the varargs, you must follow some rules otherwise program code won't compile. The rules are as follows:

  • There can be only one variable argument in the method.

  • Variable argument (varargs) must be the last argument.

Examples of varargs that fails to compile:

  1.     

  2. void method(String... a, int... b){}//Compile time error  

  3.   

  4. void method(int... a, String b){}//Compile time error  

  5.       

Example of Varargs that is the last argument in the method:

  1. class VarargsExample3{  
  2.    
  3.  static void display(int num, String... values){  
  4.   System.out.println("number is "+num);  
  5.   for(String s:values){  
  6.    System.out.println(s);  
  7.   }  
  8.  }  
  9.   
  10.  public static void main(String args[]){  
  11.   
  12.  display(500,"hello");//one argument   
  13.  display(1000,"my","name","is","varargs");//four arguments  
  14.  }   
  15. }  
  16.       

Test it Now

Output:number is 500
       hello
       number is 1000
       my
       name
       is 
       varargs