Selasa, 15 Maret 2016

Non static blocks in java example

Non Static Blocks in java

  • 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


  1. package nonstaticblocks;
  2. public class A {
  3.  
  4.    {
  5.         
  6.        System.out.println("non static block executed");
  7.  
  8.     }
  9.  
  10. }


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.
  1. package nonstaticblocks;
  2. public class A {
  3.  
  4. {

  5.   System.out.println("first block");
  6.  
  7. {
  8.  System.out.println("second block");
  9. }
  10.  
  11. {
  12.  System.out.println("third block");
  13. }
  14. public static void main(String[] args) {
  15.   A obj= new A();
  16. }
  17. }

 Output:

  1. first block
  2. second block
  3. third block


 Order of execution of non static blocks with respect to constructor?



non static blocks in java example program


Bagikan

Jangan lewatkan

Non static blocks in java example
4/ 5
Oleh

Subscribe via email

Suka dengan artikel di atas? Tambahkan email Anda untuk berlangganan.