T.K.
T.K.

Reputation: 2259

Initializing a java array

Recently, I found that an array can be initialize as follows:

private static int[] _array = new int[4];

// An arbitrary amount of code

{ 
    _array[0] = 10;
    _array[1] = 20;
    _array[2] = 30;
    _array[3] = 40;
}

What is this form of initialization called? What are its limitations?

Upvotes: 2

Views: 969

Answers (2)

lukastymo
lukastymo

Reputation: 26809

It is initialization block and regarding to documentation:

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors

I've answered yesterday in similar post here

Upvotes: 1

Mark Elliot
Mark Elliot

Reputation: 77104

This is instance member initialization using an initializer block, and it looks a lot like static initialization which would prefix that block with the word static.

Its limitations would match that of any constructor as the Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

Upvotes: 3

Related Questions