2

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?

T.K.
  • 2,229
  • 5
  • 22
  • 26

2 Answers2

3

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.

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
  • 3
    It's also worth noting that this seems like a very dangerous way to initialize an array referenced by a **static** variable. Each time a new instance is created, the array's previous contents are lost and it is reinitialized to a new set of values. If that's desirable, then `_array` should probably be an instance member. – Mark Peters Apr 05 '11 at 21:23
  • @Mark Pardon my curiosity, but is the difference between "member initialization" and "static initialization" only that the member initialization is called each in each constructor for a new instance, whereas static initialization is called only ever once? – T.K. Apr 05 '11 at 21:31
  • @T.K.:Semantically, a static initializer is run once each time the class is loaded by the class loader. In most cases, this means just once. – Mark Peters Apr 05 '11 at 21:32
  • @T.K.: member initialization is per *instance* while static initialization is per *class*; so member initialization is called every time a new instance is created, while static initialization will be called only the very first time the class is referenced. – Mark Elliot Apr 05 '11 at 21:33
1

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

Community
  • 1
  • 1
lukastymo
  • 26,145
  • 14
  • 53
  • 66