java静态变量的加载时机 2021/10/3
结论放前面:如果不涉及到具体的创建类和方法调用,那么被static final修饰的基本类型以及字符串常量的赋值会在链接的准备阶段完成,其余的静态变量会在初始化阶段完成。
首先我们要知道java虚拟机在准备阶段和初始化阶段会做什么事情。
- 准备:为static变量分配空间,设置默认值。
- 初始化:执行类变量的赋值动作和静态语句
下面是代码测试
public class InitializationTest1 {
public static int a=1; //初始化
public static final int INT_CONSTANT=10; //准备
public static final Integer INTEGER_CONSTANT1=Integer.valueOf(100); //初始化
public static Integer INTEGER_CONSTANT2=Integer.valueOf(1000); //初始化
public static final String s0="helloWorld0"; //准备
public static final String s1=new String("helloWorld123"); //初始化
public static String S2="helloWorld1234"; //初始化
public static final int NUM1=new Random().nextInt(10); //初始化
}