static字段
public class Client {
public static int i = 2;
static {
i = 100;
}
public static void main(String[] args) {
System.out.println("i=" + i);
}
}
i=100
public class Client {
static {
i = 100;
}
public static int i = 2;
public static void main(String[] args) {
System.out.println("i=" + i);
}
}
i=2
结论1:静态变量是在类初始化时首先被加载的,JVM会去查找类中所有的静态声明,然后分配空间,注意这时候只是完成了地址空间的分配,还没有赋值,之后JVM会根据类中静态赋值语句(包括静态类赋值和静态块赋值)的先后顺序来执行
实例字段
public class Client {
private int i = 2;
{
i = 100;
}
public static void main(String[] args) {
System.out.println(new Client().i);
}
}
100
public class Client {
{
i = 100;
}
private int i = 2;
public static void main(String[] args) {
System.out.println(new Client().i);
}
}
2
结论2:实例字段与static字段类似