Double Brace Initialization in Java
Last Updated :
13 Sep, 2023
The combination of two separate processes in Java is known as Double Brace Initialization in Java. As the name suggests, there are two braces {{ included in it.
A single brace { is nothing new for programmers. The first brace in the double brace initialization is used to create an anonymous inner class. We have made many anonymous inner classes in such a way. The second brace is what makes it different from the normal braces in Java. The second brace is the initialization block which is used with the declared anonymous inner class. When this initialization block is used with the anonymous inner class, it is known as Java double brace initialization.
Advantages of Double Brace Initialization
- It has fewer lines of code compared to the native way of creation and initialization.
- The code is more readable.
- Creation and Initialization are done in the same expression.
Disadvantages of Double Brace Initialization
- It is Obscure and is not a widely known way to do the initialization.
- It creates an extra class every time we use it.
- It doesn’t support the use of the “diamond operator” – a feature introduced in Java 7.
- It doesn't work if the class we are trying to extend is marked as final.
- It holds a hidden reference to the enclosing instance, which may cause memory leaks.
Note: It's due to these disadvantages that double brace initialization is considered as an anti-pattern.
Implementation:
Geeks, if you are unaware of double brace initialization you are already using the standard approach that is without double brace initialization for which we have proposed a sample below as follows:
Procedure: When we use a collection in a code, we typically do the following.
- Declare a variable for a temporary collection.
- Create a new empty collection and store a reference to it in the variable.
- Put things into the collection.
- Pass the collection to the method.
Example: Standard Approach
Java
// Java program to Demonstrate Working of Collections
// Without Double Brace Initialization
// Importing required classes
import java.util.HashSet;
import java.util.Set;
// Main class
// DoubleBrace
public class GFG {
// Method 1
// Main driver method
public static void main(String[] args)
{
// Creating an empty HashSet of string entries
Set<String> sets = new HashSet<String>();
// Adding elements to Set
// using add() method
sets.add("one");
sets.add("two");
sets.add("three");
// Calling method 2 inside main() method
// Now pass above collection as parameter to method
useInSomeMethod(sets);
}
// Method 2
// Helper method
private static void useInSomeMethod(Set<String> sets)
{
// Print all elements of desired Set
// where method is invoked
System.out.println(sets);
}
}
Output explanation:
Above are normal steps we all follow in our coding practices. Don’t you feel that Java should have a more convenient syntax for collections (lists, maps, sets, etc.)? Let's see another easy way of doing it. This is known as double brace initialization. Java Double Brace Initialization is used to combine the creation and initialization in a single statement. Using double brace initialization, we can initialize collections.
Usage of Double Brace Initialization
Procedure: When we use a double brace initialization in a code, we typically do the following.
- Create an anonymous inner class that extends sets.
- Provide an instance initialization block that invokes the add method and adds the elements to the set.
- Pass the set to the method.
Example:
Java
// Java program to Demonstrate Working of Collections
// With Double Brace Initialization
// Importing required classes
import java.util.HashSet;
import java.util.Set;
// Main class
// DoubleBrace
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty HashSet
Set<String> sets = new HashSet<String>()
// Double brace
{
{
// Adding elements to above HashSet
// This is double brace initialization
add("one");
add("two");
add("three");
}
};
// ...
// Now pass above collection as parameter to method
// Calling method 2 inside main() method
useInSomeMethod(sets);
}
// Method 2
private static void useInSomeMethod(Set<String> sets)
{
// Print elements of the desired Set
// where method is invoked
System.out.println(sets);
}
}
Output Explanation: The first brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are creating a subclass of the HashSet class so that this inner class can use the add() method. The second braces are instance initializers. The code an instance initializers inside is executed whenever an instance is created.
Similar Reads
Instance Initialization Block (IIB) in Java In a Java program, operations can be performed on methods, constructors, and initialization blocks. Instance Initialization Blocks or IIBs are used to initialize instance variables. So firstly, the constructor is invoked and the java compiler copies the instance initializer block in the constructor
3 min read
Initialize a static Map in Java using Double Brace Initialization In this article, a static map is created and initialised in Java using Double Brace Initialization. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Double Brace Initialization In Double Brace Initia
2 min read
The Initializer Block in Java In order to perform any operations while assigning values to an instance data member, an initializer block is used. In simpler terms, the initializer block is used to declare/initialize the common part of various constructors of a class. It runs every time whenever the object is created. The initial
2 min read
Initialize HashMap in Java HashMap in Java is a part of the java.util package and allows storing key-value pairs. Initializing a HashMap can be done in multiple ways, including static blocks, utility methods from the Collections class, and modern approaches provided by Java 8 and Java 9. This article will guide you through th
4 min read
How to Declare and Initialize an Array in Java? An array in Java is a linear data structure that is used to store multiple values of the same data type. In an array, each element has a unique index value, which makes it easy to access individual elements. We first need to declare the size of an array because the size of the array is fixed in Java
5 min read
Initialization of local variable in a conditional block in Java Java comprises 5 conditional blocks namely - if, switch, while, for and try. In all these blocks, if the specified condition is true, the code inside the block is executed and vice-versa. Also, Java compiler doesn't let you leave a local variable uninitialized. While initializing local variable insi
3 min read