How come
int alone;
System.out.println(alone);
Gives errors but
int[] arr = new int[1];
System.out.println(arr[0]);
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.