Variable Arguments :
We can pass variable number of arguments to a function in Java. Variable arguments means passing different number of arguments to same function on different call. Variable number of arguments are represented by elipsis(...) and known as 'variable arity method'. It eliminates the need of overloading methods to pass different number of arguments.
Syntax:
returnType methodName(data_type... variableName){}
Example:
class Varargs1{
static void show(String... values){
System.out.println("show method invoked ");
for(String s:values){
System.out.println(s);
}
}
public static void main(String args[]){
show(); //zero argument
show("hey"); //one argument
show("my","name","is","varargs");//four arguments
}
}
Output:
show method invoked
show method invoked
hey
show method invoked
my
name
is
varargs
In the above example we are passing different number of arguments to show method.
0 Comment(s)