Zulfi Zulfi - 4 months ago 37
Java Question

why does accessing final static variables in class does not loads the class

public class LoadTest {
public static void main(String[] args) {
class Hello111{
static{System.out.println("i M in SIB");}
static int a=10;

When i run the above code . The class Hello111 is loaded as expected and "i M in SIB" is printed in console as expected.

But if i change the static variable in class Hello as below

static int a=10;

To final as below

final static int a=10;

And if i run the code after this simple change , class Hello111 is not loaded in JVM and the static block in Hello111 class is not executed.

I understand that defining a variable as static final makes it a "global constant". But i am not able to understand as to why JVM did not load the class when its final static member is accessed.


The compiler knows, that a constant's value cannot be changed anymore. So this value is directly used in the statement


which compiles to (the byte-code equivalent of)


meaning there is no reference to the class Hello111 anymore and it does not need to be loaded anymore.