Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static initializer block not run 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(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.

like image 936
user2210872 Avatar asked Mar 26 '13 09:03

user2210872


People also ask

When would you use a static initialization block?

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.

In which order are initialization blocks run?

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.

Will static block be executed with final variable?

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.

Can we keep static initialization blocks inside an abstract class?

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.


2 Answers

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.

like image 99
Parth Soni Avatar answered Oct 13 '22 01:10

Parth Soni


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
like image 41
AmitG Avatar answered Oct 13 '22 02:10

AmitG