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";
}
Jon Skeet
people
quotationmark

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

people

See more on this question at Stackoverflow