javastatic-blockclassloading

Why static block is not executed


As per java doc, static block is executed when the class is initialized.

Could anyone please tell me why static block is not executed when I run below code?

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

public class Main {

    public static void example1() {
        Class<?> class1 = A.class;
        System.out.println(class1);
    }


    public static void example2() {
        try {
            Class<?> class1 = Class.forName("ClassLoading_Interview_Example.ex1.A");
            System.out.println(class1);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        example1();
    }
}

Solution

  • A class's static initialization normally happens immediately before the first time one of the following events occur:

    • an instance of the class is created,
    • a static method of the class is invoked,
    • a static field of the class is assigned,
    • a non-constant static field is used, or [...]

    You are currently not doing any of the above. So, by replacing

    Class<?> class1 = A.class;
    System.out.println(class1);
    

    with this for example

    A object = new A();
    

    will give you your result.