What is Double Brace Initialization in Java?

By IncludeHelp Last updated : February 4, 2024

Double Brace Initialization

Double brace initialization is used to create an anonymous class that is derived from the specified class and provides an initializer block within that class.

Use of double brace initialization

  • To create an anonymous class derived from the specified class.
  • To initialize the objects such as a list, linked lists, stacks, etc.

Syntax of double brace initialization

Below is the syntax of double brace initialization to initialize a list:

new ArrayList<Integer>() {{
 // Initializer block
}};

Example of double brace initialization

This example creates a list, a linked list, and a stack using the double brace initialization.

// Importing the required classes
import java.util.*;

// The Main Class
public class Main {
  public static void main(String args[]) {
    // Creating an ArrayList using double brace initialization
    List < Integer > listObj = new ArrayList < Integer > () {
      {
        add(10);
        add(20);
        add(30);
      }
    };
    System.out.println("Elements of ArrayList : " + listObj.toString());

    // Creating a LinkedList using double brace initialization
    List < Integer > linkedlistObj = new LinkedList < Integer > () {
      {
        add(11);
        add(22);
      }
    };
    System.out.println("Elements of LinkedList : " + linkedlistObj.toString());

    // Creating a stack using double brace initialization
    List < Integer > stackObj = new Stack < Integer > () {
      {
        add(101);
        add(102);
      }
    };
    System.out.println("Elements of Stack : " + stackObj.toString());
  }
}

Output

The output of the above example is:

Elements of ArrayList : [10, 20, 30]
Elements of LinkedList : [11, 22]
Elements of Stack : [101, 102]

Benefits of using double brace initialization

The following are the benefits of using the double brace initialization in Java:

  • It increases the readability of the code.
  • It provides an additional initialization logic with more flexibility.
  • It makes the code more concise.

To understand this example, you should have the basic knowledge of the following Java topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.