This post will discuss the usage of the double brace initialization technique in Java.

We can use a double brace for creating and initializing Java objects in a single expression. This creates an anonymous inner class with just an instance initializer in it. This post provides an overview of some of the common usages of double brace initialization:

1. Initialize an object in Java

Download  Run Code

Output:

[Aditya, 27]

2. Initialize set in Java

3. Initialize list in Java

4. Initialize map in Java

5. Join two lists in Java

6. Join two sets in Java

 
Note that we should best avoid this technique as it costs an extra class at each usage. It also holds hidden references to the enclosing instance and any captured objects, which may cause problems with serialization or memory leaks.

That’s all about the usage of Double Brace Initialization in Java.