T
T
thatmaniscool2017-06-08 21:20:48
Java
thatmaniscool, 2017-06-08 21:20:48

What are the differences between String[] args and String...args arrays?

Sometimes I see this kind of code

String [] args
и 
String... args

What is their difference?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tarzan82, 2017-06-08
@tarzan82

An entry like methodName(T... args) is called varargs (Variable Arguments) The
convenience is that you can pass arguments at once and not create an array and the number of arguments can be 0 or N. Example:

public static void vargs(final String... strings) {
  System.out.println(strings);
}

public static void arrs(final String[] strings) {
  System.out.println(strings);
}

public static void main(final String... args) {
  vargs(); // ok
  vargs("1", "2"); // ok
    
  arrs(); // compilation error
  arrs(new String[] {"1", "2"}); // ok
}

There are a couple of points: methods with varargs cannot be overloaded and varargs must be the last argument
public static void manyParams(final String... strings, final Integer number) {
  // compilation error
}

public static void manyParams(final Integer number, final String... strings) {
  // ok
}

A
al_gon, 2017-06-08
@al_gon

https://docs.oracle.com/javase/1.5.0/docs/guide/la...
Difference:

public static void method1(final String arg0, final String[] arg1, final String arg2) {
  
}

public static void method2(final String arg0, final String... arg1, final String arg2) {
  
}

Method 1 compiles, 2 does not.
PS: Overloading doesn't work either.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question