Java – Variable Argument (Varargs):

 checkout sourcecode here

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:

            return_type method_name(data_type… variableName){}

 

Simple Example of Varargs in java:

package varargs;

public class VarargsExample1 {

    static void display(String... values) {
        System.out.println("display method invoked ");
    }

    public static void main(String args[]) {

        display();//zero argument
        display("my", "name", "is", "varargs");//four arguments
    }
}

Test it Now

Output:display method invoked
       display method invoked

 


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:

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

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

 

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

class VarargsExample3{

    static void display(int num, String... values){
        System.out.println("number is "+num);
        for(String s:values){
            System.out.println(s);
        }
    }

    public static void main(String args[]){

        display(500,"hello");//one argument   
        display(1000,"my","name","is","varargs");//four arguments  
    }
}  

Test it Now

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

Leave a Reply

Your email address will not be published. Required fields are marked *