Search code examples
javaarraysstringcurly-braces

Java Array of Strings in a Class - Curly brace error in Eclipse


I have searched SO for this, and have seen some similar questions, but not this question specifically (that I could find, anyway).

I am receiving a curly-brace / semicolon error on the lines before and after these two statements. They are members of the class (not within a class method). When I remove the array assignment line (second line), the curly-brace / semicolon error goes away. I'm dumbfounded, but know there is a simple answer to this.

public class Test {
    private int var1 = 1;

    // These are the troublesome lines
    public String[] name = new String[10];
    name[0] = "Mary"; // When I remove this line, both the errors go away

    public int var2 = 10;
}

The error(s) in Eclipse (Juno) that I am getting are:

Syntax error on token ";", { expected after this token

...on the error placed on the "var1" line, and:

Syntax error, insert "}" to complete Block

...on the "var2" line.

What am I doing wrong? I have tried different variances, like:

(String) name[0] = "Mary";

...and so on.


Solution

  • The problem is that this statement:

    name[0] = "Mary";
    

    isn't in a method, or a constructor, or an instance initializer. Only declarations (and initializers) can be at the top level of a class - not statements.

    I suggest you put it in a constructor.

    public Test() {
        names[0] = "Mary";
    }