Initializing Fields

Java provides an alternative way to initialize fields that might require a complex initialization routine. For simple values the initialization can be done in one line.

Initializing Instance Members

Instance members can be initialized inside an initialization block. Any code placed within the block will be copied to the beginning of every constructor by the compiler. This approach is used to share a block of code between multiple consturctors.

Here is a trivial example of initializing an array within an initialization block,

int[] array = new int[5];
{
    for (int j = 0; j < array.length ; j++) {
        array[j] =+ j;
    }
}

When the object is created, the new array will contain, [0, 1, 2, 3, 4].

Initializing Static Members

Complex static field initialization routines that require more than one line, or some other logic can be initialized in a static initialization block. A static initialization block is a normal block of code enclosed in braces, {}, and preceded by the static keyword.

static int[] array = new int[5];
static {
    for (int j = 0; j < array.length ; j++) {
        array[j] =+ j;
    }
}

results matching ""

    No results matching ""