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.
A constant is called perfect constant if it is declare as static final. When compiler compiling class y & while compiling sop(Z.x) it replace sop(Z.x) with sop(10) bcz x is a perfect constant that it means in byte code class Y not use class Z so while running class Y class Z is not load thats why SIB of class Z is not execute.
So, when you call
Z.x
as below:It won't initialize the class, except when you call that
Z.x
it will get thatx
from that fixed memory location.Static block is runs when JVM loads
class Z
. Which is never get loaded here because it can access thatx
from directly without loading the class.The reason is that when jvm load a class, it put all the class's constant members into the constant area, when you need them, just call them directly by the class name, that is to say, it needn't to instantiate the class of Z. so the static initialization block is not executed.
If X wouldn't have been final, in that case JVM have to load the class 'Z' and then only static block would be executed. Now JVM need not to load the 'Z' class so static block is not executed.
compile time Z.x value becomes 10, because
so compiler creates code like given below, after inline
It does not run because the class is never loaded.
Since the
x
field onZ
has been declared withstatic final
they are created in a fixed memory location. Accessing this field does not require the class to be loaded.