Why doesn't my static block of code execute?

java, static

Solution

The problem is that `A.a` is a constant variable.

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.

Therefore your `Manager.main` method is compiled exactly as if it were:

public static void main(String ...arg) {
    System.out.println("main");
    System.out.println(9);
}

There's no real reference to `A.a` any more, so the `A` class doesn't even need to exist, let alone be initialized. (You can delete `A.class` and still run `Manager`.)

If you're relying on using `A.a` to make sure the type is initialized, you shouldn't add a no-op method instead:

public static void ensureClassIsInitialized() {
} 

then just call that from your `main` method. It's very unusual to need to do this though.

Problem

I am trying to run this code, I but found out this behavior of final with static: the code runs without executing static block of A. Please provide me with the reason. ``` class A { final static int a=9; static { //this block is not executing ?? System.out.println("static block of A"); } } class Manager { static { System.out.println("manager sib"); } public static void main(String ...arg) { System.out.println("main"); System.out.println(A.a); } } ``` Why doesn't the static block of Class A run?

Original source