Java – when we call a static final variable, why not execute the static block first

See English answers > static block in Java not executed

class Test4 {
     public static void main(String as[]) {
         System.out.println(Hello.x); 
     }

}

class Hello {
    final static int x=10;
    static {
        System.out.println("Hello");                
    }
}

Output: 10

According to my knowledge, why not print hello? If we call static variables and load the first class, when loading the class, it should first execute the static block, and then send the static variables

Solution

Performs a static initialization block when the class containing it is initialized - usually when the class is loaded

You can say that when you access hello in class test4 X, the JVM should load and initialize the class hello However, this will not happen here because it is a special case

Static final constants are inlined by the compiler – this means that when this code is compiled, hello. In the main method X is replaced by the value of the constant at compile time with 10 In essence, your code is compiled into the same bytecode as when you compile it:

class Test4 {
    public static void main(String[] args) {
        System.out.println(10); // Inlined constant value here!
    }
}

class Hello {
    final static int x = 10;
    static {
        System.out.println("Hello");                
    }
}

Note that in this case, class test4 does not actually access class Hello - so class Hello is not loaded and the static initializer is not executed when test4 is run

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>