Empty arrays automatically initialize contents?

后端 未结 5 1741
滥情空心
滥情空心 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:57

    There are two separate by similar issues involved here. First note that all variable types have a default value, which differs depending on the type. There are at least two times where these defaults are used: 1) declaring a member variable and 2) initializing an array with the new operator.

    Notice that if you simply declare a local array variable without initializing it with new, then you get the same error as when you declare a simple int variable. This is because all local variables must be initialized. They do not get an automatic default value.

    On the other hand, member variables do get a default value. Similarly, when you create an array object by using the new operator, the elements of the array are initialized to the appropriate default value.

提交回复
热议问题