The difference between String [] a and String ... a

What is the difference when we write String [] a in the main method and String ... a?

public static void main(String[]a) 

and

 public static void main(String...a) 
+6
source share
3 answers

The first expects one parameter, which is an array of strings.

The second takes zero or more String parameters. It also accepts an array of strings.

+8
source
 public static void main(String[] a) 

This should be called with a single argument of type String [] or null.

 public static void main(String...a) 

This call can be called with a single argument of type String [], OR with any number of String arguments, for example main ("a", "b", "c"). However, the compiler will complain if you pass null, as it cannot determine if you have a String [] value of null or an array of 1 null string.

Inside main() in any case, the variable a is equal to String[] .

Since this is main , you may not think about what it will be called ... Usually this is the first. But I switched to using the second form for all my networks; it is easier to pass arguments for testing.

+8
source

The second is called varargs and was introduced in Java 5. It frees you from explicitly creating an array when you need to go to zero or more parameters to a method.

+3
source

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


All Articles