Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an array as a function parameter: "not a statement" (Java)

Tags:

java

string

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
like image 413
Sara Avatar asked Jan 24 '26 04:01

Sara


1 Answers

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");
like image 163
arshajii Avatar answered Jan 26 '26 17:01

arshajii