Double Brace Initialization in Java!

java-double-brace-initializationFew days back I came to know about a different way of initializing collections and objects in Java. Although this method of initialization has been there in Java since quite a few years now, very few people actually knows about it or have used it in their code. The technique is called Double Brace Initialization technique in Java.

Let us see first how we will initialize an ArrayList in Java by “normal” way:

List<String> countries = new ArrayList<String>();
countries.add("Switzerland");
countries.add("France");
countries.add("Germany");
countries.add("Italy");
countries.add("India");

Above code snippet first creates an object of ArrayList type String and then add one by one countries in it.

Now check the Double Brace Initialization of the same code:

List<String> countries = new ArrayList<String>() {{
	add("India");
	add("Switzerland");
	add("Italy");
	add("France");
	add("Germany");
}};

How does this works?

Well, the double brace ( {{ .. }} ) initialization in Java works this way. The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an “instance initializer”, because it is declared withing the instance scope of the class — “static initializers” are a related concept where the keyword static is placed before the brace that starts the block, and which is executed at the class level as soon as the classloader completes loading the class . The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors.

If you have not understood the concept, try executing following code and it will make things clear for you.

public class Test {
	public Test() {
		System.out.println("Constructor called");
	}
	static {
		System.out.println("Static block called");
	}
	
	{
		System.out.println("Instance initializer called");
	}
	
	public static void main(String[] args) {
		new Test();
		new Test();
	}
}

Output:

Static block called
Instance initializer called
Constructor called
Instance initializer called
Constructor called

Thus the instance initializer code will be called each time a new instance of object is created.



9 Comments

  • ruslan 27 June, 2009, 2:03

    Unfortunatelly that code creates anonymous class. Multiple using of such technique will create dozen of anonymous classes, and that could cause problems with perm gen space.

  • Viral Patel 27 June, 2009, 14:30

    I agree with you Ruslan. This technique is not efficient way of doing this, but I dint knew if such thing exists :-)

  • Karthik 28 June, 2009, 19:00

    I agree with Viral that many Java developers will not be knowing it unless they read the specification. Nice to know that such an option exists.

  • Prashanth 6 July, 2009, 18:28

    Interesting to know with clean explanation

  • Daniel 28 February, 2011, 15:00

    Javas Double Brace Instatiation makes it a lot easier to read your source code. For review reasons is that important to you and your colleagues. I think most people only see these advantages if nobody uses them: they would be glad to have them.

    A few tips and backgrounds, too: is is about the obstacles and the possibillities with Javas Double Brace Instatiation:
    http://bit.ly/endUIi

    I hope I could help a little.

  • Ravi 4 April, 2012, 17:47

    Awesome! Never tried such a thing so far. This could be useful in providing easy fixes.

    Thanks

  • Raghu 13 June, 2013, 13:44

    Hi,

    Anybody please help me , how to send /receive sms from/to java web application/java application.

  • Dharmendra 7 August, 2013, 11:55

    Nice explanation…Thanks a lot for this article.

  • Vinay 18 March, 2014, 23:24
    import java.util.ArrayList;
    import java.util.List;
    import java.lang.*;
     
    public class MyBasicArrayList {
     
        public static void main(String[] a){
    
          long beginTime = System.currentTimeMillis();
            List<String> al = new ArrayList<String>(){{
              add("JAVA");
            add("C++");
            add("PERL");
            add("PHP");  
            }};
            long endTime = System.currentTimeMillis();
            long difference1 = endTime - beginTime;
                    System.out.println(al);
            
            long beginTime2 = System.currentTimeMillis();
            List<String> a2 = new ArrayList<String>();
            a2.add("JAVA");
             a2.add("C++");
             a2.add("PERL");
             a2.add("PHP");  
             long endTime2 = System.currentTimeMillis();
            long difference2 = endTime2 - beginTime2;
            System.out.println(al);
            //add elements to the ArrayList
            if(difference2>difference1){
                System.out.println("{{}} Wins");}
                else{
                    System.out.println("{{}} Looses");}           
        }
    }
     

    I tried this program and Guess what {{}} Looses….. n times So I appreciate your effort but this is lil slower think..kindly revert If I am wrong.

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current day month ye@r *