public class Test {
public static void main(String[] args) {
System.out.println(Hello.a1);
}
}
class Hello {
static final int a1=10;
static {
System.out.println("SB");
}
}
This code is always printing 10 but not printing SB.Why?
A static final
field is implemented as a compile-time constant which is replicated in the accessing method/class without any reference to the context of definition (its class). This is why accessing it does not trigger the static class block.
This is basically due to the final
keyword. If you remove final
as follows:
public class Test {
public static void main(String[] args) {
System.out.println(Hello.a1);
}
}
class Hello{
static int a1=10;
static{
System.out.println("SB");
}
}
You will see that SB
is printed as expected.
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