static变量初始化 java,在Java中初始化静态变量

What exactly is meant by "Static variables are initialized when a class is loaded"? I read lots of discussions available on the net but still I am confused. Step 2 is be the initialization step, right? Then what happens in step 1 "when the class is loaded"?

public class NewClass {

static int[] arr; //Step 1

NewClass(){

arr = new int[10]; //Step 2

for(int i= 0;i<10;i++){

arr[i] = i;

}

}

}

解决方案

Step 2 is be the initialization step, right?

No, It's called construction of array. The initialization of array means putting things into it that you are doing after step 2.

Then what happens in step 1 "when the class is loaded"?

when the class is loaded all static variables are initialized with their default values. In case of Object it's default value is null or you can say a reference that is pointing to nothing. No memory is allocated to array at this point of time.

What happens till Step 2 ?

When the object of type NewClass is created using keyword new at that time constructor is called and the array is constructed and memory is assigned for 10 int values in the heap with all zero as default value (till step 2)

What happens after Step 2?

After Step 2 you are actually initializing the array i.e putting the values in it.

static int[] arr; // declaration

arr = new int[10]; // construction

arr[i] = i; // initialization

If you want to read more about it then read book SCJP Sun Certified Programmer for Java 6

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值