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