Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my static block of code execute?

Tags:

java

static

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?

like image 853
Sandepp1 Avatar asked Feb 17 '23 02:02

Sandepp1


1 Answers

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.

like image 114
Jon Skeet Avatar answered Mar 01 '23 12:03

Jon Skeet