Double brace initialization in Java


Double braces can be used to create and initialize objects in a single Java expression. See the example below −

Example

import java.util.ArrayList;
import java.util.List;

public class Tester{
   public static void main(String args[]) {

      List<String> list = new ArrayList<>();

      list.add("A");
      list.add("B");
      list.add("C");
      list.add("D");
      list.add("E");
      list.add("F");
      System.out.println(list);

      List<String> list1 = new ArrayList<String>() {
      {
         add("A"); add("B");add("C");
         add("D");add("E");add("F");
      }
      };

      System.out.println(list1);
   }
}

Output

[A, B, C, D, E, F]
[A, B, C, D, E, F]
  • In order to initialize first list, we first declared it and then call its add() method multiple times to add elements to it.

  • In second case, we have created an anonymous class extending the ArrayList.

  • Using braces, we've provided an initializer block calling the add methods().

  • So by using braces, we can reduce the number of expressions required to create and initialize an object.

Updated on: 21-Jun-2020

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements