This Java program always prints only 10, but not SB.Why?

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 always prints 10, but not SB.Why?

+5
source share
3 answers
Field

A static final implemented as a compile-time constant that is replicated in an access method / class without reference to the definition context (its class). This is why access to it does not call a static class.

This is mainly 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 the SB prints as expected.

+10
source

A static finite constant variable is used. This variable will be replaced at compile time with an actual constant value to improve performance. If you look at the compiled binary (yes, you cannot;), but technically speaking with an assumption), it will be something similar to this:

 public class Test { public static void main(String[] args) { System.out.println(10); // Constant } } class Hello { static final int a1=10; static { System.out.println("SB"); } } 

Based on this code, the Hello class will not be loaded into RAM. Therefore, he will not print SB.

+5
source

Your static code block will be called when you instantiate the class. Try the following:

 public class Test { public static void main(String[] args) { Hello h = new Hello(); System.out.println(Hello.a1); } } class Hello { static final int a1 = 10; static { System.out.println("SB"); } } 
-3
source

All Articles