- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the order of execution of non-static blocks with respect to a constructor in Java?
Whenever an object is created, a non-static block will be executed before the execution of the constructor.
Non-Static Blocks
- The Non-static blocks are class level blocks which do not have any prototype.
- The need for a non-static block is to execute any logic whenever an object is created irrespective of the constructor.
- The Non-static blocks are automatically called by the JVM for every object creation in the java stack area.
- We can create any number of Non-static blocks in Java.
- The order of execution of non-static blocks is an order as they are defined.
Example
public class NonStaticBlockTest { { System.out.println("First Non-Static Block"); // first non-static block } { System.out.println("Second Non-Static Block"); // second non-static block } { System.out.println("Third Non-Static Block"); // third non-static block } NonStaticBlockTest() { System.out.println("Execution of a Constructor"); // Constructor } public static void main(String args[]) { NonStaticBlockTest nsbt1 = new NonStaticBlockTest(); NonStaticBlockTest nsbt2 = new NonStaticBlockTest(); } }
Output
First Non-Static Block Second Non-Static Block Third Non-Static Block Execution of a Constructor First Non-Static Block Second Non-Static Block Third Non-Static Block Execution of a Constructor
Advertisements