What are the differences between a static block and a constructor in Java?


Static block

  • The static blocks are executed at the time of class loading.
  • The static blocks are executed before running the main () method.
  • The static blocks don't have any name in its prototype.
  • If we want any logic that needs to be executed at the time of class loading that logic needs to placed inside the static block so that it will be executed at the time of class loading.

Syntax

static {
   //some statements
}

Example

Live Demo

public class StaticBlockTest {
   static {
      System.out.println("Static Block!");
   }
   public static void main(String args[]) {
      System.out.println("Welcome to Tutorials Point!");
   }
}

Output

Static Block!
Welcome to Tutorials Point!


Constructor

  • A Constructor will be executed while creating an object in Java.
  • A Constructor is called while creating an object of a class.
  • The name of a constructor must be always the same name as a class.
  • A Constructor is called only once for an object and it is called as many times as we can create an object. i.e The constructor gets executed automatically when the object is created.

Syntax

public class MyClass {
   //This is the constructor
   MyClass() {
      // some statements
   }
}

Example

Live Demo

public class ConstructorTest {
   static {
      //static block
      System.out.println("In Static Block!");
   }
   public ConstructorTest() {
      System.out.println("In a first constructor!");
   }
   public ConstructorTest(int c) {
      System.out.println("In a second constructor!");
   }
   public static void main(String args[]) {
      ConstructorTest ct1 = new ConstructorTest();
      ConstructorTest ct2 = new ConstructorTest(10);
   }
}

Output

In Static Block!
In a first constructor!
In a second constructor!

Updated on: 11-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements