Init block and static init block in java
Init block gets executed every time right before the constructor.
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