Why static block is not executed
Asked Answered
D

2

8

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();
    }
}
Dual answered 16/3, 2018 at 8:55 Comment(0)
S
5

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.

Stevenage answered 16/3, 2018 at 11:28 Comment(2)
So what happens when i execute this line "Class<?> class1 = A.class;". Would not the JVM load class A?Dual
@SridharSrinivasan If you execute this line the JVM will load the class, but will not initialize it as a class initialization happens according to a set of rules (see my quote above) and this is not included in those rules.Stevenage
Y
2

Referencing A.class will not resulting in executing A's static initializers, see here

Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class.

And

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

T is a class and an instance of T is created.

A static method declared by T is invoked.

A static field declared by T is assigned.

A static field declared by T is used and the field is not a constant variable (§4.12.4).

Yorke answered 16/3, 2018 at 11:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.