Reputation: 13
What is the difference between void method(String[] a)
and void method(String... a)
?
The first method take an array of Strings where as the second method takes one or more String arguments. What are the different features that they provide?
Moreover, don't know why but this is working:
public class Test {
public static void main(String[] args) {
String[] a = {"Hello", "World"};
Test t = new Test();
t.method(a);
}
void method(String...args) {
System.out.println("Varargs"); // prints Varargs
}
}
Upvotes: 1
Views: 6617
Reputation: 16498
Not nice, but sometimes very usefull: If at time of writing your code you do not know which args your method gets as input your code would look like
public class Test {
public static void main(String[] args) {
Test t = new Test();
String[] a = {"Hello", "World"};
Integer [] b = {1,2};
t.method(a);
t.method(b);
t.method('a',1,"String",2.3);
}
void method(Object...args) {
for (Object arg : args){
System.out.println(arg);
}
}
Upvotes: 0
Reputation: 3785
The only difference is when you invoke the method, and the possible ways to invoke it as varargs allow multiple strings separated by "," or the use of an array as a parameter.
Important Note:
varargs feature automates and hides the process of multiple args passed in an array.
Edit:
Java doesn't allow this public void method(String ... args, String user)
as varargs
must be the last parameter to be called.
Upvotes: 2
Reputation: 9427
There is no difference, only if there are other elements after it in the signature.
For instance:
public void method(String[] args, String user){}
is possible, since there is no way the jvm will think user
is still an element of args
.
public void method(String ... args, String user){}
will cause trouble, though.
Upvotes: 8