Sara
Sara

Reputation: 499

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

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

Upvotes: 3

Views: 175

Answers (3)

Nirbhay Mishra
Nirbhay Mishra

Reputation: 1648

This Is because when you pass {"string1","string2"} as the argument of the method It does not know what it is what to expect of it.

As per the document the syntax is only allowed when you declare and instantiate array variable at the same time

int[] a={1,4,8,6}; //allowed

this will make array of int having length equal to the number of values passed in the parenthesis . . so you can pass anonymous array object like this

method(new int[]{2,4,8,9});

but not like method({2,4,8,9});

Upvotes: 1

arshajii
arshajii

Reputation: 129537

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

Upvotes: 6

jlordo
jlordo

Reputation: 37823

You need

myFunction(new String[]{"string1", "string2"});

The syntax is explained in the Java Language Specification, Chapter 10.2 Array Variables

Upvotes: 3

Related Questions