Empty arrays automatically initialize contents?

后端 未结 5 1709
滥情空心
滥情空心 2021-01-16 13:35

How come

int alone;
System.out.println(alone);

Gives errors but

 int[] arr = new int[1];
 System.out.println(arr[0]);
         


        
5条回答
  •  太阳男子
    2021-01-16 13:53

    It depends on where it was declared (inside a class vice inside a function). If it is a class member variable it will be initialized to its default. 0 for numeric types(0.0 for float types / double), null for Strings, false for boolean,and null for Objects. If it is declared inside of a function it would remain uninitialized in the case of int alone. In terms of an array it will always initialize the values contained within it.

提交回复
热议问题