posted 19 years ago
The meaningful difference in the two situations is that the values in an array (whether they are primitives, as in "int [] x", or objects, as in "String [] x") are assigned a default value, just the same as instance variables. Method-local (automatic) variables are not.
In the case of the array, the array variable arr is a method-local variable - and therefore must be initialized before it is accessed, or a compiler error will be found.
But once the array is instantiated, the individual elements within the array need not be initialized - they get their default value, which is null for object types, 0 for numeric values, false for booleans, etc.
I broke out one of the lines in your example to show the distinction:
Another thing that might help is to think of reference variables as having three states:
1. declared, but not initialized - gives the "might not have been initialized" compiler error when you try to access it
2. declared and initialized, but null - gives "NullPointerException" runtime exception when you try to access it (apply the dot operator on it).
3. declared and referencing an object (not null) - everyone's happy
Instance variables and array elements get to skip state # 1 - they are automatically initialized to null. So you can't ever get a "might not have been initialized" compiler error.
Local variables (like your "A s" in your first program) can be in all three states.
Note, state 2 doesn't apply when you're talking about a primitive, which can't be null. It's either uninitialized (if it's local and you have not assigned a value), or set.
Hope this helps.
-- Jon