What is the difference between Static Block and Constructor placed in a class?
Table of Contents
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.
Hello! I am Narayanaswamy founder and admin of narayanatutorial.com. I have been working in the IT industry for more than 12 years. NarayanaTutorial is my web technologies blog. My specialties are Java / J2EE, Spring, Hibernate, Struts, Webservices, PHP, Oracle, MySQL, SQLServer, Web Hosting, Website Development, and IAM(ForgeRock) Specialist
I am a self-learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.