Sequence of execution of, instance method, static block and constructor in java?


A static block is a block of code with a static keyword. In general, these are used to initialize the static members of a class. JVM executes static blocks before the main method at the time loading a class.

Example

public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}

Output

Hello this is a static block
This is main method

A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type.

public class MyClass {
   MyClass(){
      System.out.println("Hello this is a constructor");
   }
   public static void main(String args[]){
      new MyClass();
   }
}

Output

Hello this is a constructor

Instance method

These are the normal methods of a class (non static), you need to invoke them using an object of the class −

Example

public class MyClass {
   public void demo(){
      System.out.println("Hello this is an instance method");
   }
   public static void main(String args[]){
      new MyClass().demo();
   }
}

Output

Hello this is an instance method

Order of execution

When you have all the three in one class, the static blocks are executed first, followed by constructors and then the instance methods.

Example

public class ExampleClass {
   static{
      System.out.println("Hello this is a static block");
   }
   ExampleClass(){
      System.out.println("Hello this a constructor");
   }
   public static void demo() {
      System.out.println("Hello this is an instance method");
   }
   public static void main(String args[]){
      new ExampleClass().demo();
   }
}

Output

Hello this is a static block
Hello this a constructor
Hello this is an instance method

Updated on: 02-Jul-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements