Init Block and Static init Block in Java

Init block and static init block in java

{ static
//Init block {
} //static init block
}

Init block gets executed everytime right before the constructer.

Whereas static init block gets executed only once in the life of the program.

static init block gets executed at the time of the loading of the class in the JRE(Java Runtime Environment).

At the time of loading static init block executedthen searching of main starts.

//Demo for init block and static init block .

class InitDemo

{

InitDemo(int x)

{

System.out.println("1-arg const");

}

InitDemo()

{

System.out.println("no-arg const");

}

static

{

System.out.println("static init block");

}

{

 

System.out.println("First Instance init block");

}

public static void main(String [] args)

{

System.out.println("Main Started");

InitDemo obj=new InitDemo();

InitDemo obj2=new InitDemo(7);

}

}

Output


Image-1.jpg

Ebook Download
View all
Learn
View all