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

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

I am new to Java programming. Can someone tell me what the difference is between ( String....args ) and ( String [] args ) If I use the first instead of the second ........ Does it really matter?

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

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

One of the differences spring cannot make from these observations is that in the second case (but not in the first), the caller may have an array reference. In both cases, the method works with args as an array of strings, but if it does something like swap elements of the array, it will not be visible to the caller if the String... args form is used.

+6
source share
3 answers

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

+14
source

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

JLS-12.1.4. Invoke Test.main says (partially)

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

 public static void main(String[] args) public static void main(String... args) 

Not explicitly stated (but also allowed)

 public static void main(String args[]) 
+7
source

There are very few differences in the main method, they will work the same.

String ... is known as varargs. The surface to varargs is a very good syntactic sugar that allows you to indefinitely define method invocation arguments. In the body method, varargs is treated exactly like an array of type.

The disadvantage of varargs is Java, which converts undefined arguments to a new array, creating garbage. Alternatively, you can use method overloading to emulate varargs if garbage creation should be zero.

+1
source

Source: https://habr.com/ru/post/989433/


All Articles