I have a function that takes a String[] argument. How is it possible that this:
String[] string = {"string1", "string2"};
myFunction(string);
works, whereas this:
myFunction({"string1", "string2"});
doesn't? It gives me the error:
Illegal start of expression not a statement ";" expected
The standalone {"string1", "string2"} is syntactic sugar: the compiler can infer what it is supposed to be only when you are declaring and initializing your array. On it's own, however, this syntax will not work:
String[] s1 = {"abc"}; // works
String[] s2;
s2 = {"abc"}; // error, need to explicitly use 'new String[]{"abc"}'
Just as an aside, in your case you might be able to avoid the explicit array creation by using varargs:
void myFunction(String... args) {
// args is a String[]
}
...
myFunction("string1", "string2");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With