While accessing final static variable with class name why static block is not being processed in java?
class Foo {
public static final int BAR;
static {
System.out.println("Hello");
}
}
class Baz {
public static void quux() {
System.out.println(Foo.BAR);
}
}
In a Java class, a static block is a set of instructions that is run only once when a class is loaded into memory. A static block is also called a static initialization block. This is because it is an option for initializing or setting up the class at run-time.
Unlike C++, Java supports a special block, called a static block (also called static clause) that can be used for static initialization of a class. This code inside the static block is executed only once: the first time the class is loaded into memory.
Static block code executes only once during the class loading. The static blocks always execute first before the main() method in Java because the compiler stores them in memory at the time of class loading and before the object creation.
Therefore, only one time static block will be executed. Note: Instance block and constructor both are executed during the object creation but instance block will execute first before the execution of the constructor during the object creation.
It will sometimes - it depends on whether the variable is actually a constant:
If that's the case, any references to the variable are effectively turned into the value. So in this code:
class Foo {
public static final int BAR = 5;
}
class Baz {
public static void quux() {
System.out.println(Foo.BAR);
}
}
The method in Baz
is compiled into the same code as:
public static void quux() {
System.out.println(5);
}
There's no hint of Foo.BAR
left in the bytecode, therefore Foo
doesn't need to be initialized when the method executes.
If you want to prevent that from happening, you always just make it not be initialized with a constant expression in a variable initializer. For example:
class Foo {
public static final int BAR;
static {
BAR = 5;
}
}
class Baz {
public static void quux() {
System.out.println(Foo.BAR);
}
}
That would be enough to make Foo.BAR
not count as a constant as far as the compiler is concerned.
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