10.7 Static Initializer Blocks
Java allows static initializer blocks to be defined in a class. Although such blocks can include arbitrary code, they are primarily used for initializing static fields. The code in a static initializer block is executed only once, when the class is loaded and initialized.
Local variables in static and instance initializer blocks can be declared with the reserved type name var—that is, local variable type inference using var is permitted for local variable declarations in initializer blocks. Code in the rest of this chapter shows many examples of such declarations.
The syntax of a static initializer block comprises the keyword static followed by a local block that can contain arbitrary code, as shown at (3) in the declaration of the following class:
class MatrixData {
static final int ROWS = 12, COLUMNS = 10; // (1)
static long[][] matrix = new long[ROWS][COLUMNS]; // (2)
// …
static { // (3) Static initializer
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = 2*i + j;
}
// …
}
When the class MatrixData is first loaded, the static final fields at (1) are initialized. Then the array of arrays matrix of specified size is created at (2), followed by the execution of the static block at (3).
Note that the static initializer block is not contained in any method. A class can have more than one static initializer block. Initializer blocks are not members of a class, and they cannot have a return statement because they cannot be called directly.
When a class is initialized, the initializer expressions in static field declarations and static initializer blocks are executed in the order in which they are specified in the class. In the class MatrixData, the initializer expressions at (1) and (2) are executed before the static initializer block at (3).
Similar restrictions apply to static initializer blocks as for static initializer expressions: The keywords this and super cannot occur in a static initializer block, as such a block defines a static context.
Leave a Reply