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.
Static blocks can be used to initialize static variables or to call a static method. However, an instance block is executed every time an instance of the class is created, and it can be used to initialize the instance data members.
Initialization blocks run in the same order in which they appear in the program. Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces.
We can initialize a final static variable at the time of declaration. Initialize inside a static block : We can also initialize a final static variable inside a static block because we should initialize a final static variable before class and we know that static block is executed before main() method.
We're allowed to use the abstract keyword in a static initialization block. This can only be done when defining a class, by declaring the class itself abstract , and optionally some of its methods.
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.
compile time Z.x value becomes 10, because
static final int x=10; is constant
so compiler creates code like given below, after inline
System.out.println(10); //which is not calling Z class at runtime
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With