Why static initializer block not run in this simple case?

initialization, java, load, static

Solution

Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class

So, when you call `Z.x` as below:

System.out.println(Z.x);

It won't initialize the class, except when you call that `Z.x` it will get that `x` from that fixed memory location.

Static block is runs when JVM loads `class Z`. Which is never get loaded here because it can access that `x` from directly without loading the class.

Problem

``` class Z { static final int x=10; static { System.out.println("SIB"); } } public class Y { public static void main(String[] args) { System.out.println(Z.x); } } ``` Output :10 why static initialization block not load in this case?? when static x call so all the static member of class z must be load at least once but static initialization block not loading.

Original source

Related problems