Any block declared inside global area not prefix with static keyword is known as non static block.
Characteristics of non static block
- non static block doesn't have any name.
- non static block doesn't have any formal arguments.
- non static block doesn't have any return type.
- non static block executed automatically (implicitly) by the compiler.
- Programmer can not call non static block.
Ex.
- class Instagram
- {
- public static void main(String [ ] args)
- {
- Instagram ref1 = new Instagram( );
- Instagram ref2 = new Instagram( );
- Instagram ref3 = new Instagram( );
- System.out.println(("ME");
- }
- {
- System.out.println(("Congratulations your a/c has been created successfully..!");
- }
- } Congratulations your a/c has been created successfully..!
Output:
Congratulations your a/c has been created successfully..!
Congratulations your a/c has been created successfully..!
Congratulations your a/c has been created successfully..!
Congratulations your a/c has been created successfully..!
Tracing
Note:
non static block gets executed only when we create object but only once.
why do we need non static block?
To execute some statements mandatorily whenever we create object.
Difference between static and Non static block:
0 Comments