Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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)
like image 479
Surbhi Avatar asked Jul 02 '11 12:07

Surbhi


3 Answers

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.

like image 85
Karoly Horvath Avatar answered Sep 22 '22 23:09

Karoly Horvath


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.

like image 30
david van brink Avatar answered Sep 23 '22 23:09

david van brink


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.

like image 41
Sanjay T. Sharma Avatar answered Sep 22 '22 23:09

Sanjay T. Sharma