What is the execution order of blocks, static blocks, constructors, and methods in Java?

Initialization blocks (blocks and static blocks) and constructors in a Java class are executed in following sequence:

1. static block
2. block
3. constructor
4. method

The rules are for determining the execution order are -

1. Static blocks get executed at the time of class loading.
2. Instance blocks get executed only when object is created using new keyword.
3. Constructors get executed only when object is created using new keyword.

Let's take a look at following Java code example that demonstrates the exection order of initialization blocks (blocks and static blocks) and constructors in a Java class.

public class Test { 
    static {
        System.out.println("static block executed");
    }
 
    {
        System.out.println("block executed");
    }
 
    public Test() {
        System.out.println("constructor executed");
    }
 
    public void fun() {
        System.out.println("fun executed");
    }
 
    public static void main(String args[ ])  {
        System.out.println("main started");
        new Test().fun();
    } 
} 
 
OUTPUT
======
static block executed 
main started
block executed
constructor executed
fun executed

Hope you have enjoyed reading What is the execution order of blocks, static blocks, constructors, and methods in Java?. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.