Whats the difference when we write String[]a in main method and String...a?
public static void main(String[]a)
and
public static void main(String...a)
The first one expect one parameter, which is an array of Strings.
The second one accepts zero or more String parameters. It also accepts an array of Strings.
public static void main(String[] a)
This one must be called with a single argument of type String[], or null.
public static void main(String...a)
This one can be called with a single argument of type String[], OR with any number of String arguments, like main("a","b","c"). However, the compiler will complain if you pass null, since it can't tell if you mean a String[] of value null, or an array of 1 null string.
Inside main()
, in either case, the variable a
is a String[]
.
Since it's main
, you might not think about how it would be called... Usually it's the first thing. But I've switched to using the second form for all my mains; it's easier to pass arguments to it for testing.
The second one is called varargs and were introduced in Java 5. It relieves you from explicitly creating an array when you need to pass in zero or more parameters to a method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With