What is the difference between Static Block and Constructor placed in a class?

 

What is the difference between Static Block and Constructor placed in a class?

 

Static Block

Static block of a java class executes for only one time when JVM loads the class irrespective of whether object is created for class or not and whether java class is having main method or not. So static block is Class-Level one time execution block.

Constructor

Constructor executes automatically when object for java class is created. If you create multiple objects for java class, the constructor executes for multiple no.of times on one time for object basis.

So constructor is called Object-Level one time execution block

 

In case of Class.forName(), How will it work?

When you load java class programmatically by using Class.forName() method the static block of loaded class executes automatically.

Ex:

package narayanatutorial;

public class StaticVsConstructor2 {

    static {
        System.out.println("StaticVsConsturcor2 Static Block Executed...");
    }
}






package narayanatutorial;

public class StaticVsConstructor {

    static {
        System.out.println("Static Block Executed...");
    }

    StaticVsConstructor() {
        System.out.println("Constuctor Block Executed..");
    }

    public static void main(String args[]) throws ClassNotFoundException {
        System.out.println("Main Method Executed...");
        StaticVsConstructor ex1 = new StaticVsConstructor();
        StaticVsConstructor ex2 = new StaticVsConstructor();
        Class.forName("narayanatutorial.StaticVsConstructor2");
       
    }
}


Output

Static Block Executed...
Main Method Executed...
Constuctor Block Executed..
Constuctor Block Executed..
StaticVsConsturcor2 Static Block Executed...

In order to make DriverManager establishing connection with database software, we need to register JDBC Driver Class object with DriverManger as show below

 

oracle.jdbc.driver.OracleDriver od=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(od);

 

I hope you understood the difference between static block and constructor placed in a class. Please reply in comments.

 

Leave a Reply