Skip to main content

Posts

Showing posts with the label Initializer Blocks

How To Use Initializer Blocks in Java?

Initializer Blocks - what are they, why & how are they used? These blocks are similar to the static initialization blocks with the only difference being the absence of the 'static' keyword. The Java compiler copies all the initializer blocks in the same order as they are in the source code in every constructor before any executable statement in that constructor. public class InitializationWithInitializerBlock{ public static int staticIntField = 100; private boolean instanceBoolField; {      boolean y;                 y = true; //or, y = <some expression returning a boolean value>;      instanceBoolField = y; } } So if you see all your constructors having same code-segment at the top then you will probably be better off keeping that in an initializer block as anyway the compiler would copy the block in every constructor at the t...