
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements