AllJava

Understanding Blocks in Java

Java provides several ways of instantiating objects / classes. One of the most interesting features being blocks.
Java gives you an option to create two types of blocks –

  • Initializer blocks
  • Static blocks

Initializer blocks popularly known as Instance initializers are used to do something when an Object is created. Simple program below demonstrates a block :
[ad#in-blog]

package com.roadtobe.supaldubey.examples.java;
public class InstanceInitliazer
{
private String id;
private String name;
{
id = java.util.UUID.randomUUID().toString();
}
}

[Q:] Ok! Whatever, So what have I achieved ?
[A:] These initializers come handy  when you have multiple constructors and want to invoke some code before the constructor. Java actually copies the code to the beginning of the constructor for you.
Now static initalizers are executed once at the time class is loaded. Lets look at sample code –

package com.roadtobe.supaldubey.examples.java;
public class StaticInstanceInitliazer
{
private String id;
private String name;
static
{
   id = java.util.UUID.randomUUID().toString();
   System.out.println("I am a static block");
}
}

You can have any number of such blocks in your Java code.
[Q] – Seems fine! “But” Where do I use static blocks ?
[A] – Static blocks should be used to do something once the class is loaded. This would be executed once and only once while the class resides in memory. Usual application is to initialize the final properties. [Yes! you read it right, static blocks can initialize final instances / variables]
Lets see how –

package com.roadtobe.supaldubey.examples.java;
public class StaticInstanceInitliazerFinal
{
private final static List CARS;
static {
List list = new ArrayList();
list.add("Maruti");
list.add("TATA");
list.add("FIAT");
CARS = Collections.unmodifiableList(list);
}
// ....
}

Some thumb rules –

  • If you have multiple constructors calling some basic code, look into using block / instance initializers.
  • They make your code look clean.
  • Use them to initialize final and static members if they use some complex logic such as loading of properties / creating a list etc.

Do post your comments / questions if you have. I will be happy to help.

Leave a Reply

Your email address will not be published. Required fields are marked *