Skip to main content

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 top. This way you can at least make the code more readable, maintainable (as the common code will only be at one place), and if the size of common code is significant and if you have multiple constructors then using initializer block you can also reduce the size of your source code.

 public class InitializerBlocks {
 
 public static void main(String[] args) {
 new InitializerBlocks();
 }
 //Constructor - 1
 public InitializerBlocks(){
 System.out.println("3");
 }
 //Initializer Block - 1
 {
 System.out.println("1");
 }
 //Initializer Block - 2
 {
 System.out.println("2");
 }
 }
 
 Output
 
 1
 2
 3
 
 
(Of course the above code is not making a good use of initializer blocks as they not initializing anything what they are actually meant to. The purpose here is just to show how a Java compiler places all the initializer blocks at the top in every constructor in the same order as they appear in the code.)

Alternative to Initializer Blocks in Java
You can use an instance method to initialize an instance field - in most of the cases you would like to make this instance method as 'final' as there will hardly be any need for the subclasses to override such a method (evidently, a non-final instance method would also do the job). Similarly if you need to call the method only from within the same class, you would probably make it 'private'. Read more about how to pick access modifiers -


 public class InitializationWithPrivateInstanceMethod{
 
 public static int staticIntField = 100;
 private boolean instanceBoolField = privInstanceMeth();
 
 private final boolean privInstanceMeth() {
      boolean y;
      //computing the value of y
      y = <some expression returning boolean>;
      return y;
 }
 }
 
 
The advantage of using an instance method over an initializer block is that it gives you flexibility of re-initializing those instance fields by calling the corresponding final instance method(s) in some setter or in some other method. Another interesting scenario where you can't use an initializer block and you would probably need an instance method to do it for you:


Suppose you have a need of using the code of initializer block in any of your sub-classes and suppose all your constructors have extra code as well in addition to the initializer block code which would be added to them on the top during compilation. Now in such a situation, if you need to set only those fields which are set in the initializer block then you can't do that directly in your subclass as the most you can do here is to call a super class constructor (that too would normally re-set all the instance fields) ... right?


Having a final instance method would solve your problem here. Choosing a suitable access specifier will again follow the same rules what has been discussed in article mentioned in above paragraph. In this case since the sub-classes require access to that method, so choosing 'protected' as the access specifier should be fine.

Comments

Popular posts from this blog

Advantages & Disadvantages of Synchronous / Asynchronous Communications?

  Asynchronous Communication Advantages: Requests need not be targeted to specific server. Service need not be available when request is made. No blocking, so resources could be freed.  Could use connectionless protocol Disadvantages: Response times are unpredictable. Error handling usually more complex.  Usually requires connection-oriented protocol.  Harder to design apps Synchronous Communication Advantages: Easy to program Outcome is known immediately  Error recovery easier (usually)  Better real-time response (usually) Disadvantages: Service must be up and ready. Requestor blocks, held resources are “tied up”.  Usually requires connection-oriented protocol

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag

XML Binding with JAXB 2.0 - Tutorial

Java Architecture for XML Binding (JAXB) is an API/framework that binds XML schema to Java representations. Java objects may then subsequently be used to marshal or unmarshal XML documents. Marshalling an XML document means creating an XML document from Java objects. Unmarshalling means creating creating a Java representation of an XML document (or, in effect, the reverse of marshaling). You retrieve the element and attribute values of the XML document from the Java representation. The JAXB 2.0 specification is implemented in JWSDP 2.0. JAXB 2.0 has some new features, which facilitate the marshalling and unmarshalling of an XML document. JAXB 2.0 also allows you to map a Java object to an XML document or an XML Schema. Some of the new features in JAXB 2.0 include: Smaller runtime libraries are required for JAXB 2.0, which require lesser runtime memory. Significantly, fewer Java classes are generated from a schema, compared to JAXB 1.0. For each top-level complexType, 2.0 generates a v