What is the "String ..." in java?

Possible duplicate:
varargs and the '...' argument
Java, 3 points in parameters

I saw this definition in a javascript file for Android. It looks the same as String []. Are they different? Thanks.

+6
source share
5 answers

varags . If the method signature is method(Param param, String... x) , then for an object of type Param one Param and any number of String objects are required.

Have a couple if it's cool:

  • This is nothing special. It is just a candied mass. So, method(MyObject... o) same as method(MyObject[] o) .

  • Vararg should be the last parameter in the argument list.

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

+13
source

Syntax for writing array elements as parameter

eg:

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

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

javacompiler will independently create an array of parameters.

+5
source

This is for defining a method with a variable number of arguments .

+1
source

This is vararg, a variable number of arguments. In the body of the method, you consider it as String [], but when you call the method, you can either select the String [] string or simply list your values.

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

It was introduced with Java 5.

+1
source

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

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

public void foo(String[] arg){}

you must pass an array:

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

If the method is defined as:

public void foo(String arg){}

You can call it

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

or

foo("a", "b");

0
source

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


All Articles