JVM Knowledge

If a declarator in a field declaration has a variable initializer, then the declarator has the semantics of an assignment (§15.26) to the declared variable.

If the declarator is for a class variable (that is, a static field), then the following rules apply to its initializer:

  • It is a compile-time error if a reference by simple name to any instance variable occurs in the initializer.

  • It is a compile-time error if the keyword this (§15.8.3) or the keyword super (§15.11.2, §15.12) occurs in the initializer.

  • At run time, the initializer is evaluated and the assignment performed exactly once, when the class is initialized (§12.4.2).

    Note that static fields that are constant variables (§4.12.4) are initialized before other static fields (§12.4.2). This also applies in interfaces (§9.3.1). When such fields are referenced by simple name, they will never be observed to have their default initial values (§4.12.5).

If the declarator is for an instance variable (that is, a field that is not static), then the following rules apply to its initializer:

  • The initializer may refer by simple name to any class variable declared in or inherited by the class, even one whose declaration occurs to the right of the initializer (§3.5).
  • The initializer may refer to the current object using the keyword this (§15.8.3) or the keyword super (§15.11.2, §15.12).
  • At run time, the initializer is evaluated and the assignment performed each time an instance of the class is created (§12.5).

References from variable initializers to fields that may not yet be initialized are subject to additional restrictions, as specified in §8.3.3 and §16 (Definite Assignment).

Exception checking for a variable initializer in a field declaration is specified in §11.2.3.

Variable initializers are also used in local variable declaration statements (§14.4), where the initializer is evaluated and the assignment performed each time the local variable declaration statement is executed.

Example 8.3.2-1. Field Initialization

class Point {
    int x = 1, y = 5;
}
class Test {
    public static void main(String[] args) {
        Point p = new Point();
        System.out.println(p.x + ", " + p.y);
    }
}

This program produces the output:

1, 5

because the assignments to x and y occur whenever a new Point is created.

Example 8.3.2-2. Forward Reference to a Class Variable

class Test {
    float f = j;
    static int j = 1;
}

This program compiles without error; it initializes j to 1 when class Test is initialized, and initializes f to the current value of j every time an instance of class Test is created.