in case of local variables, they must be initialised or error occurs. But in case of array variable it initialises automatically to zero. How and Why? i was trying out this code expecting an error. but the values in a are initialised to '0'.
because arrays in java are objects. and an object must have valid initialization state if you don't explicitly initialize it.
for e.g we have a Dog class and your create new Dog object in main method
Dog d = new Dog(); // here d is a local variable but it has been initialized to new Dog. so when Dog object gets created and assuming that you have not provided any constructor the various dog fields will be initialized to their respective defaults.
same is with int array.
int a = new int; // a is of the type int array which points to integer array object that acts as a container with 3 partitions and those partitions are initialized to 0 which is default value of int.
if you have Dog d = new Dog // this would result in a dog array which would have been initialized to null values rather than any garbage values
Ok so like the instance variables of class dog are initialised through dog() default constructor, the values in array object are initialized automatically. but is this a work of default constructor in this array case? whats the constructor name? is it a?
Here the variable "a" is declared, and it is initialized. It is initialized by assigning that array with three elements to it.
So that's it for the variable "a", it's initialized to an array. But you're asking about the contents of the array, which is a separate question.
Array elements are always initialized to zero, if they are primitives, or to null if they are object references. So since this is an array of primitives, the array elements are all initialized to zero.
JLS 10.6 wrote:
The length of the array to be constructed is equal to the number of variable initializers immediately enclosed by the braces of the array initializer. Space is allocated for a new array of that length. If there is insufficient space to allocate the array, evaluation of the array initializer completes abruptly by throwing an OutOfMemoryError. Otherwise, a one-dimensional array is created of the specified length, and each component of the array is initialized to its default value (§4.12.5).