3

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
1
  • That's the initialization notation. Commented Jul 10, 2013 at 13:42

3 Answers 3

6

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");
Sign up to request clarification or add additional context in comments.

4 Comments

I could use varargs, but in my case, my function take 3 parameters : int, String[] and Object[], so I think it's not possible...
@Sara Sure it is, if you make the varargs String the last argument. e.g. void f(int x, Object[] y, String... z) {}.
Yes, but I have the same "problem" with the object[]. I prefer to stay consistent and not use varargs here, because it means I should use it only for string[] or for object[]. I don't think that would be very elegant ^^
@Sara It all depends on the context of your program. What you do in the end is up to you.
3

You need

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

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

2 Comments

give me a second ;) Searching the JLS
@arshajii: the short answer is that the simple {} notation is only valid for initialization (i.e. when assigning a value to a variable at the point where it's declared). Everywhere else you need to use the explicit new String[] {}.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.