All Java developers may not be familiar with double brace initialization and could be wondering what is that. Not all books on Core Java mention this form of initialization. If we go by the literal meaning of it, then we must be using double braces (which is {{) for some kind of initialization.

double braces in java

It does the job what it says but then how is it different from normal initialization of objects and collections where we use new operator and then invoke setters/add/put methods. The difference lies in the fact that we get a place where we can add initialization code immediately when creating the object. Consider for example, we have a Java Bean with some properties and getter/setters as listed below:

Double Brace Initialization (DBI) sample code

public class Test {

	int a;
	String b;
	float c;
	
	public int getA() {
		return a;
	}
	public void setA(int a) {
		this.a = a;
	}
	public String getB() {
		return b;
	}
	public void setB(String b) {
		this.b = b;
	}
	public float getC() {
		return c;
	}
	public void setC(float c) {
		this.c = c;
	}
	
	public static void main(String[] args) {
		Test t = new Test() {{
			setA(10);
			setB("test");
			setC(12.1f);
		}};
		
		System.out.println(t.getA() + " " + t.getB() + " "  + t.getC());
	}
}

The output of running the above code is:

10 test 12.1

Understanding Double Brace Initialization

In normal scenario, we would have created an instance of Test class and then invoked the setter methods to initialize the instance. But double brace initialization is providing us a compact way to initialize our objects.

We can also use this form of initialization for any kind of objects including collections and swing controls etc.

In fact, we can call double brace initialization as instance initializer block. Please note that this form of initialization is not applicable for static fields and we need to use static initializer block for static field initialization.

Let us now have a look at how this form of object initialization works in the background:

When we use double brace initialization, an anonymous inner class is created and the code under the initializer block is placed under it as instance member initialization. In our case, the de-compiled version of Test.class is:

De-compiled Code

There are two class files being created for our code example.

import java.io.PrintStream;

public class Test
{

    int a;
    String b;
    float c;

    public Test()
    {
    }

    public int getA()
    {
        return a;
    }

    public void setA(int a)
    {
        this.a = a;
    }

    public String getB()
    {
        return b;
    }

    public void setB(String b)
    {
        this.b = b;
    }

    public float getC()
    {
        return c;
    }

    public void setC(float c)
    {
        this.c = c;
    }

    public static void main(String args[])
    {
        Test t = new Test() {

            
            {
                setA(10);
                setB("test");
                setC(12.1F);
            }
        };
        System.out.println((new StringBuilder(String.valueOf(t.getA()))).append(" ").append(t.getB()).append(" ").append(t.getC()).toString());
    }
}

Also there is an inner class created as Test$1.class whose de-compiled version is listed below:

// Referenced classes of package com.sample:
//            Test

class setC extends Test
{

    ()
    {
        setA(10);
        setB("test");
        setC(12.1F);
    }
}

We can clearly see that a class named setC (the name depends upon JVM being used) is created with an instance initializer block which provides values for member variables of the super class Test.

Advantages of double brace initialization

  • The code is more readable for fellow developers who will be working on the code at a later stage because the creation and declaration of objects has been combined at a single place.
  • This form of initialization is helpful in code reviews.

Disadvantages of double brace initialization

  • For every double brace initialization block, a separate anonymous inner class is created and loaded. If there a large number of such initializer blocks in an application, it can run out of memory.
  • The serialization of the Test class in our case will also cause the serialization of inner class which is setC in our case. This means that Serialization operation also got expensive.
  • The instance that we get out of double brace initialization is an instance of anonymous inner class i.e. In our case t is an instance of type Test$1. Where as without DBI, we get an instance of type Test.class. This can cause issues while using the traditional form of equals method where we intermediately compare the class of the two objects to determine if they are equal or not.

The following source code and output demonstrates the above point.

public class Test {

	int a;
	String b;
	float c;
	
	public int getA() {
		return a;
	}
	public void setA(int a) {
		this.a = a;
	}
	public String getB() {
		return b;
	}
	public void setB(String b) {
		this.b = b;
	}
	public float getC() {
		return c;
	}
	public void setC(float c) {
		this.c = c;
	}
	
	public static void main(String[] args) {
		Test t = new Test() {{
			setA(10);
			setB("test");
			setC(12.1f);
		}};
		Test t1 = new Test();
		
		System.out.println(t.getClass());
		System.out.println(t1.getClass());
	}
}

Output:

class com.sample.Test$1
class com.sample.Test

Reference

1) http://c2.com/cgi/wiki?DoubleBraceInitialization

Related Posts

What is Double Brace Initialization in Java admin Core Java
All Java developers may not be familiar with double brace initialization and could be wondering what is that. Not all books on Core Java mention this form of initialization. If we go by the literal meaning of it, then we must be using double braces (which is {{) for...
<p>All Java developers may not be familiar with double brace initialization and could be wondering what is that. Not all books on <a href="http://www.javaexperience.com/category/core-java/">Core Java</a> mention this form of initialization. If we go by the literal meaning of it, then we must be using double braces (which is {{) for some kind of initialization. <a href="http://www.javaexperience.com/wp-content/uploads/2012/11/double-braces-in-java.jpg"><img src="http://www.javaexperience.com/wp-content/uploads/2012/11/double-braces-in-java-300x300.jpg" alt="double braces in java" width="300" height="300" class="alignnone size-medium wp-image-4697" /></a> It does the job what it says but then how is it different from normal initialization of objects and collections where we use new operator and then invoke setters/add/put methods. The difference lies in the fact that we get a place where we can add initialization code immediately when creating the object. Consider for example, we have a Java Bean with some properties and getter/setters as listed below:</p> <h2>Double Brace Initialization (DBI) sample code</h2> 1 The output of running the above code is: <blockquote>10 test 12.1</blockquote> <h2>Understanding Double Brace Initialization</h2> <p>In normal scenario, we would have created an instance of Test class and then invoked the setter methods to initialize the instance. But double brace initialization is providing us a compact way to initialize our objects. We can also use this form of initialization for any kind of objects including collections and swing controls etc. In fact, we can call double brace initialization as instance initializer block. Please note that this form of initialization is not applicable for static fields and we need to use static initializer block for static field initialization. Let us now have a look at how this form of object initialization works in the background: <strong>When we use double brace initialization, an anonymous inner class is created</strong> and the code under the initializer block is placed under it as instance member initialization. In our case, the de-compiled version of Test.class is: </p> <h2>De-compiled Code</h2> There are two class files being created for our code example. 1 Also there is an inner class created as Test$1.class whose de-compiled version is listed below: 1 <p>We can clearly see that a class named setC (the name depends upon JVM being used) is created with an instance initializer block which provides values for member variables of the super class Test.</p> <h2>Advantages of double brace initialization</h2> <ul> <li> The code is more readable for fellow developers who will be working on the code at a later stage because the creation and declaration of objects has been combined at a single place.</li> <li> This form of initialization is helpful in code reviews.</li> </ul> <h2>Disadvantages of double brace initialization</h2> <p> <ul> <li> For every double brace initialization block, a separate anonymous inner class is created and <a href="http://www.javaexperience.com/java-class-loading/">loaded</a>. If there a large number of such initializer blocks in an application, it can run out of memory.</li> <li> The serialization of the Test class in our case will also cause the serialization of inner class which is setC in our case. This means that Serialization operation also got expensive.</li> <li> The instance that we get out of double brace initialization is an instance of anonymous inner class i.e. In our case t is an instance of type Test$1. Where as without DBI, we get an instance of type Test.class. This can cause issues while using the traditional form of equals method where we intermediately compare the class of the two objects to determine if they are equal or not.</li> </ul> The following source code and output demonstrates the above point. </p> 1 Output: <blockquote>class com.sample.Test$1 class com.sample.Test</blockquote> <h2>Reference</h2> 1) http://c2.com/cgi/wiki?DoubleBraceInitialization
finally executes finally
Understanding working of System.out.println
The following two tabs change content below.
I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.

Latest posts by admin (see all)

Comments

comments