Reputation: 35547
In java we can define main()
method as both these ways.
public static void main(String[] args) {
System.out.println("Hello World");
}
.
public static void main(String... args) {
System.out.println("Hello World");
}
Both method takes array
of String
arguments. Now consider following scenario.
String[] arr=new String[10]; // valid
String... arr=new String[10];// invalid
Java
never allows to create an array like this wayString... arr=new String[10];
. But in above method implementation java
allows to do so. My question is how java
achieve this two different behavior for two scenarios?
Upvotes: 0
Views: 35154
Reputation: 68715
...
is a syntax for method arguments and not for variable definitions. The name of this notation is varargs, which is self explanatory i.e variable number of arguments.
Upvotes: 4
Reputation: 17622
...
refers to varargs and its main intention to make method more readable.
void method(String... args) {
}
can be called as
method("a");
OR method("a", "b");
OR method("a", "b", "c");
I see no point in using it in variable declaration, we can't do much with
String... a = {"a", "b"}
An array can anyways be declared with dynamic size
String[] arr = {"a"};
OR
String[] arr = {"a", "b"};
Upvotes: 1
Reputation: 76057
You can use varargs in main
because a method declared with varargs (...) is bytecode compatible with a declaration of a method with an array argument (for backwards compatibility). That does not mean that the same syntax is allowed for type declarations.
Upvotes: 0
Reputation: 7836
Variable argument or varargs(...) in Java used to write more flexible methods which can accept as many argument as you need not for initialization.
Upvotes: 1