Is there any difference between String... args and String[] args in Java?

4k views Asked by At

What is the difference between String... args and String[] args in Java?

I'm new to Java programming. Can anyone plz tell me what's the difference between (String....args) & (String [] args) If I'll use first one in place of the second........Does it make any difference?

String... args will declare a method that expects a variable number of String arguments. The number of arguments can be anything at all: including zero.

String[] args and the equivalent String args[] will declare a method that expects exactly one argument: an array of strings.

One difference that might not spring out from those observations is that in the second case (but not the first) the caller may have a reference to the array. In both cases the method works with args as an array of Strings, but if it does things like swap the array elements this will not be visible to the caller if the String... args form is used.

3

There are 3 answers

1
Elliott Frisch On

There is no difference. And String... args is allowed.

JLS-12.1.4. Invoke Test.main says (in part)

The method main must be declared public, static, and void. It must specify a formal parameter (ยง8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:

public static void main(String[] args)


public static void main(String... args)

Not explicitly listed (but also allowed)

public static void main(String args[])
0
Jire On

In the main method there is very little difference, they will both work the same way.

String... is known as varargs. The upside to varargs is it is very nice syntactic sugar which lets you indefinitely define arguments to a method call. In the method's body varargs is treated exactly as an array of the type.

The downside to varargs is Java will convert the indefinite arguments to a new array, thus creating garbage. As an alternative you can use method overloading to emulate varargs if garbage creation must be zero.

3
Evgeniy Dorofeev On

If you have void x(String...args) method, you can call it as x("1", "2", "3") while void x(String[] args) can be called only as x(new String[] {"1", "2", "3"}).