8

Possible Duplicate:
varargs and the '…' argument
Java, 3 dots in parameters

I saw this definition in my android java file. It looks just like String[]. Are they different? Thank you.

Community
  • 1
  • 1
AnothrWu
  • 121
  • 1
  • 2
  • 8

5 Answers5

17

varags. If a method signature is method(Param param, String... x) it will take one Param type of object and any number of String objects.

There are couple if cool things about it:

  1. It's nothing special. It's just sugared array. So, method(MyObject... o) is same as method(MyObject[] o).

  2. Vararg has to be the last parameter in argument list.

  3. There is this funny thing that bit me once. method(MyObject... o) can be called as method() without any compilation error. Java will internally convert the no-arg call to method(new MyObject[0]). So, be aware of this.

Nishant
  • 54,584
  • 13
  • 112
  • 127
7

It's syntax for writing the items of the array as a parameter

for instance:

 public String first (String... values) {
     return values[0];
 }

Then you can call this method with first("4","2","5","67")

The javacompiler will create an array of the parameters on its own.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

It's a vararg, variable number of arguments. In the method body you treat it as a String[], but when you call the method you can either chose to supply a String[] or simply enumerate your values.

void foo(String... blah) { }

void bar() {
   String[] a = { "hello", "world" };
   foo(a);  // call with String[]
   foo("hello", "world"); // or simply enumerate items
}

Was introduced with Java 5.

user1252434
  • 2,083
  • 1
  • 15
  • 21
1

It's for defining a method with a variable number of arguments.

alexg
  • 3,015
  • 3
  • 23
  • 36
0

String is a string type. String[] is an array of strings.

String ... is a syntactic sugar named ellipsis, introduced in java 1.5 and taken from C. It can be used in methods definitions and actually the same as array with only one difference. If method is defined as:

public void foo(String[] arg){}

you must pass array to it:

foo(new String[] {"a", "b"});

If method is defined as:

public void foo(String arg){}

You can call it either

foo(new String[] {"a", "b"});

or

foo("a", "b");

AlexR
  • 114,158
  • 16
  • 130
  • 208