So I'm declaring and initializing an int array:
static final int UN = 0;
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = UN;
}
Say I do this instead...
int[] arr = new int[5];
System.out.println(arr[0]);
... 0
will print to standard out. Also, if I do this:
static final int UN = 0;
int[] arr = new int[5];
System.out.println(arr[0]==UN);
... true
will print to standard out. So how is Java initializing my array by default? Is it safe to assume that the default initialization is setting the array indices to 0
which would mean I don't have to loop through the array and initialize it?
Thanks.
Every class in Java have a constructor ( A constructor is a method which is called when a new object is created , which initializes the fields of the class variables ) . So when you are creating an instance of the class , constructor method is called while creating the object and all the data values are initialized at that time .
For object of integer array type all values in the array are initialized to 0(zero) in the constructor method . Similarly for object of boolean array , all values are initialized to false .
So Java is initializing the array by running it's constructor method while creating the object