Home » Android » android – What is "String…" in java?

android – What is "String…" in java?

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

How to&Answers:

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.

Answer:

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.

Answer:

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.

Answer:

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

Answer:

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");