3

Code:

String Foo[];
Foo={"foo","Foo"};

Error at Line 2: Illegal Start of expression
The code works if I say:

String Foo[]={"foo","Foo"};

Why does this happen, and how should I do the required without generating an error? This also happens with other data types.

Would appreciate if you could explain in layman terms.

4
  • 4
    The compiler want's you to specifiy that {"foo", ...} is meant to be an array, so use new String[]{"foo", ...}. Besides that, do yourself a favor and let variable names start with a lower case character, i.e. String foo instead of String Foo (and I personally like to have the array declaration at the type, i.e. String[] foo). Commented Sep 24, 2018 at 9:24
  • Initialization and Assignment these are two words that makes the difference. I believe. :) Commented Sep 24, 2018 at 9:28
  • FYI: alternatively, for unmodifiable list rather than simple array, List<String> list = List.of( "foo" , "bar" ) ; as a single line or two lines. Commented Sep 24, 2018 at 9:30
  • normally you have to use new String[] { ...} (this was an always must in earlier versions of Java), but, as a syntactic sugar, the compiler accepts just { ... } in a field declaration or variable declaration. Why? it is specified that way in the Java Language Specification (probably it would be to messy to accept it everywhere) Commented Sep 24, 2018 at 9:44

2 Answers 2

3

{"foo","Foo"} is an array initializer and it isn't a complete array creation expression:

An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.

Java Specification

Use new String[] {"foo","Foo"} instead.

Sign up to request clarification or add additional context in comments.

3 Comments

What does '§' mean?
@StephenAllen a link to a specification section
@StephenAllen actually it is just an abbreviation for Section Sign - apple.stackexchange.com/q/176968 or en.wiktionary.org/wiki§ (happens to be a link to the given section in the Java Language Specification)
1

You have to initialize the string array:

String foo[] = new String[]{"foo, "Foo"}; Or 
String foo[] = {"foo, "Foo"};

Modern IDEs give error for not initializing the array objects. You can refer more details here: http://grails.asia/java-string-array-declaration

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.