Search code examples
javaobjectblock

Declaring and Instantiating inside a class block


In the Class Block:

Instead of making an Object (In this case a simple String) like this:

public String one = "Hello!";

I wanted to do it like this:

String one;
one = "Hello!";

but compiler throws:

error: <identifier> expected

Why? Why the second has to be within a method?


Solution

  • It is more than likely that

    one = "Hello!"
    

    is located in the class block. This statement must be appear inside a code block — that is; a method, constructor or static initializer. E.g.:

    void myMethod() {
        String one;
        one = "Hello!";
    }
    

    Non declarative statements cannot appear in the class block.