Non Static Blocks in java
What is the need of Non static blocks in java?
Who will execute Non static blocks?
How many Non static blocks we can create?
Order of execution of non static blocks
Output:
Order of execution of non static blocks with respect to constructor?
- When ever object created non static blocks will be executed before the execution of constructor
- Non static blocks are class level block which does not have prototype
- package nonstaticblocks;
- public class A {
- {
- System.out.println("non static block executed");
- }
- }
What is the need of Non static blocks in java?
- To execute any logic whenever object is created irrespective of constructor used in object creation.
Who will execute Non static blocks?
- Non static blocks are automatically called by JVM for every object creation in java stack area
How many Non static blocks we can create?
- We can create any number of Non static blocks
Order of execution of non static blocks
- Order of execution of non static blocks will be order as they are defined.
- package nonstaticblocks;
- public class A {
- {
- System.out.println("first block");
- }
- {
- System.out.println("second block");
- }
- {
- System.out.println("third block");
- }
- public static void main(String[] args) {
- A obj= new A();
- }
- }
Output:
- first block
- second block
- third block
Order of execution of non static blocks with respect to constructor?
nice explanation of all the topics.
ReplyDeletenice
ReplyDeletestatic block gets executed when class loads not when object created.
ReplyDeletesorry , yeah true its non static block , take back my statement.
ReplyDeleteExcellent examples, thanks for spreading the knowledge
ReplyDelete