Any static initializers declared in a class are executed when the class is initialized and, together with any field initializers (§8.3.2) for class variables, may be used to initialize the class variables of the class (§12.4).
StaticInitializer:
static
Block
It is a compile-time error for a static initializer to be able to complete abruptly (§14.1, §15.5) with a checked exception (§11.2).
The static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope. This restriction is designed to catch, at compile time, circular or otherwise malformed initializations. Thus, both:
class Z { static int i = j + 2; static int j = 4; }
class Z { static { i = j + 2; } static int i, j; static { j = 4; } }
result in compile-time errors.
Accesses to class variables by methods are not checked in this way, so:
class Z { static int peek() { return j; }
static int i = peek(); static int j = 1; }
class Test { public static void main(String[] args) { System.out.println(Z.i); }
}
0
because the variable initializer for i
uses the class method peek
to access the
value of the variable j
before j
has been initialized by its variable initializer, at
which point it still has its default value (§4.5.4).
If a return
statement (§14.15) appears anywhere within a static initializer, then a compile-time error occurs.
If the keyword this
(§15.7.2) or the keyword super
(§15.10, §15.11) appears anywhere within a static initializer, then a compile-time error occurs.