What is the default initialization of an array in Java?

后端 未结 7 872
我在风中等你
我在风中等你 2020-11-22 16:30

So I\'m declaring and initializing an int array:

static final int UN = 0;
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
    arr[i] = UN;
}
<         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 16:49

    Every class in Java have a constructor ( a constructor is a method which is called when a new object is created, which initializes the fields of the class variables ). So when you are creating an instance of the class, constructor method is called while creating the object and all the data values are initialized at that time.

    For object of integer array type all values in the array are initialized to 0(zero) in the constructor method. Similarly for object of boolean array, all values are initialized to false.

    So Java is initializing the array by running its constructor method while creating the object

提交回复
热议问题