Surbhi
Surbhi

Reputation: 111

Difference between String[]a and String...a

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)

Upvotes: 6

Views: 1589

Answers (3)

Karoly Horvath
Karoly Horvath

Reputation: 96326

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.

Upvotes: 8

david van brink
david van brink

Reputation: 3652

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.

Upvotes: 8

Sanjay T. Sharma
Sanjay T. Sharma

Reputation: 23248

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.

Upvotes: 3

Related Questions