Varargs enable a method to receive zero or numerous arguments, offering a more flexible alternative compared to using overloaded methods or arrays as parameters, which can create maintenance issues. When the number of arguments to be passed into a method is uncertain, varargs provide a more convenient solution.
Advantage of Varargs
Avoiding the need for overloaded methods results in a more concise codebase.
Syntax of varargs
Varargs in C programming are denoted by an ellipsis, which consists of three dots placed after the data type. The syntax for using varargs is as shown below:
Example
return_type method_name(data_type... variableName){}
Simple Example of Java Varargs
Example
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
}
}
Example
Output:display method invoked
display method invoked
Another Program of Varargs in java:
Example
class VarargsExample2{
static void display(String... values){
System.out.println("display method invoked ");
for(String s:values){
System.out.println(s);
}
}
public static void main(String args[]){
display();//zero argument
display("hello");//one argument
display("my","name","is","varargs");//four arguments
}
}
Example
Output:display method invoked
display method invoked
hello
display method invoked
my
name
is
varargs
Rules for varargs:
When working with varargs, it is essential to adhere to specific guidelines; otherwise, the program will fail to compile. These guidelines include:
- Ensuring only a single variable argument is present in the method.
- Placing the variable argument (varargs) as the final argument in the method signature.
Examples of varargs that fails to compile:
Example
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:
Example
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
}
}
Example
Output:number is 500
hello
number is 1000
my
name
is
varargs