Google News
logo
Full Stack Developer - Interview Questions
What is double brace initialization in Java and where it is used?
In Java, double brace initialization is a combination of two separate processes. The two consecutive curly braces {{ involved in it.
 
The first curly brace represents the creation of an anonymous inner class. Remember that the second curly brace will not be considered in such a case. It is just like creating an anonymous inner class.
 
The second curly brace represents an initialization block that we have seen in it as a class for initialization. When we use the initialization block for an anonymous inner class it becomes Java double brace initialization. The inner class has a reference to the enclosing outer class. We can use the reference by using this pointer.
 
It is used to initialize collections because it is easier to initialize a constant collection using double brace initialization. The example of double brace initialization is as follows :
import java.util.*;  
public class Demo  
{  
public static void main(String args[])  
{  
-------------------  
-------------------  
Map<String, Map<String, Integer>> map = new HashMap <String, Map<String, Integer>> {{  
put ("VEGETABLES", new HashMap<String, Integer>() {{  
put("Tomato", 300);  
put("Onion", 50);  
put("Carrot", 100);  
put("Beetroot", 40);  
}}  
--------------------  
-------------------  
);  
}};  
System.out.println(map);  
}  
}​
  
Advertisement