What is the default initialization of an array in Java?

后端 未结 7 879
我在风中等你
我在风中等你 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:36

    Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.

    • For references (anything that holds an object) that is null.
    • For int/short/byte/long that is a 0.
    • For float/double that is a 0.0
    • For booleans that is a false.
    • For char that is the null character '\u0000' (whose decimal equivalent is 0).

    When you create an array of something, all entries are also zeroed. So your array contains five zeros right after it is created by new.

    Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.

提交回复
热议问题