Why does the static initializer block not start in this simple case?

class Z { static final int x=10; static { System.out.println("SIB"); } } public class Y { public static void main(String[] args) { System.out.println(Zx); } } 

Output: 10 why does the static initialization block not load in this case? when static x calls so that all static members of class z must be loaded at least once, but the static initialization block does not load.

+6
source share
6 answers

Fields that have a static modifier in their declaration are called static fields or class variables . They are associated with the class, and not with any object. Each instance of a class has a class that resides in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without instantiating the class.

So, when you call Zx as below:

 System.out.println(Zx); 

It will not initialize the class, except when you call it Zx , it will get this x from this fixed memory.

The static block starts when the JVM loads class Z Which is never loaded here because it can access this x directly without loading the class.

+1
source

Zx compilation time becomes 10 because

 static final int x=10; is constant 

therefore, the compiler creates the code as shown below after the line

 System.out.println(10); //which is not calling Z class at runtime 
+1
source

The reason is that when jvm loads the class, it puts all the members of the class constant in the constant region when you need them, just call them directly by the class name, that is, you do not need to instantiate the class Z. therefore, the static initialization block is not executed.

+1
source

It does not start because the class never loads.

 public class Y { public static void main(String[] args) { Z z new Z(); //will load class System.out.println(Zx); } } 

Since the x field on Z was declared using static final , they are created in a fixed memory location. Access to this field does not require class loading.

0
source

If X were not final, then the JVM should load the class 'Z', and then only the static block will execute. Now the JVM does not need to load the class "Z", so the static block is not executed.

0
source

A constant is called a perfect constant if it is declared as static final. When the compiler compiles the class y and when compiling sop (Zx), it replaces sop (Zx) with sop (10) bcz x is an ideal constant, which means that the class Z is not used in the byte code of the class Y, so when the class Y is run, the class Z does not load, so the class Z SIB is not run.

0
source

All Articles