public class ConstClass{
static {
System.out.println("ConstClass init!");
}
public static final String HELLOWORLD = "hello world";
}
public class NotInitialization{
public static void main(String[] args){
System.out.println(ConstClass.HELLOWORLD);
}
}
上述代码运行后,没有输出“ConstClass init!”,这是因为虽然在java源码中引用了ConstClass类中的常量HELLOWORLD,但其实在编译阶段通过常量传播优化,已经将此常量的值“hello world”存储到了NotInitialization类的常量池中。