Initializer block contains the code that is always executed whenever an instance is created. It is used to declare/initialize the common part of various constructors of a class. For example,
Common part of constructors invoked!! Default Constructor invoked Common part of constructors invoked!! Parametrized constructor invoked
We can note that the contents of initializer block are executed whenever any constructor is invoked (before the constructor’s contents)
The order of initialization constructors and initializer block doesn’t matter, initializer block is always executed before constructor. See this for example.
Refer below article for more details in instance initialization:
Instance Initialization Block (IIB) in Java
What if we want to execute some code once for all objects of a class?
We use Static Block in Java
This article is contributed by Ashutosh Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Java.util.BitSet class methods in Java with Examples | Set 2
- Shadowing of static functions in Java
- How does default virtual behavior differ in C++ and Java ?
- How are Java objects stored in memory?
- How are parameters passed in Java?
- Are static local variables allowed in Java?
- final variables in Java
- Default constructor in Java
- Assigning values to static final variables in Java
- Comparison of Exception Handling in C++ and Java
- Does Java support goto?
- Arrays in Java
- Inheritance and constructors in Java
- More restrictive access to a derived class method in Java
- Comparison of static keyword in C++ and Java