在Java中初始化静态变量 [英] Initializing static variables in java

查看:182
本文介绍了在Java中初始化静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在加载类时初始化静态变量"的确切含义是什么?我阅读了网上的许多讨论,但仍然感到困惑.步骤2是初始化步骤,对吧?那么在第1步加载类时"会发生什么?

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;
        }
    }
}

推荐答案

步骤2是初始化步骤,对吧?

Step 2 is be the initialization step, right?

不,这就是所谓的数组构造.数组的初始化意味着将步骤2之后要执行的操作放入其中.

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

然后在第1步加载类时"会发生什么?

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

在加载类时,所有静态变量都将使用其默认值进行初始化.在Object的情况下,其默认值为null,或者您可以说一个指向无内容的引用.此时没有内存分配给数组.

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.

在步骤2之前会发生什么?

What happens till Step 2 ?

在那时使用关键字new创建类型NewClass的对象时,调用了构造函数,并构造了数组,并为堆中的10个int值分配了内存,所有零均为默认值(直到第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)

步骤2之后会发生什么?

What happens after Step 2?

在第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

如果您想了解更多有关内容,请阅读 SCJP Sun Java 6认证程序员

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

这篇关于在Java中初始化静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆