Sanjay Singh
Sanjay Singh

Reputation: 362

Field initialization in java class outside the methods' bodies

Please explain below behavior, why first statement is valid while other one is invalid and throws error.

public class Test{
    private String firstName="John";// is Valid
    //Below is invalid
    private String lastName; 
    lastname="Doe";
}

Upvotes: 1

Views: 299

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500385

A class can only contain declarations (and static/instance initializers). A field declaration can contain an initializer, as per firstName - and your declaration of lastName is valid, but the assignment after it is just a statement, and a class can't directly contain statements.

If you want to separate declaration from assignment, you either need to put the assignment in a constructor:

public class Test {
    private String lastName;

    public Test() {
        lastName = "Doe";
    }
}

or use an instance initializer (less common in my experience):

public class Test {
    private String lastName;

    {
        lastName = "Doe";
    }
}

Upvotes: 9

Related Questions