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.
According to java,
Java says that the default length of a JAVA array at the time of initialization will be 10.
But the
size()
method returns the number of inserted elements in the array, and since at the time of initialization, if you have not inserted any element in the array, it will return zero.From the Java Language Specification:
Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.
null
.0
.0.0
false
.'\u0000'
(whose decimal equivalent is 0).When you create an array of something, all entries are also zeroed. So your array contains five zeros right after it is created by
new
.Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.
Thorbjørn Ravn Andersen answered for most of the data types. Since there was a heated discussion about array,
Quoting from the jls spec http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5 "array component is initialized with a default value when it is created"
I think irrespective of whether array is local or instance or class variable it will with default values
JLS clearly says
An array initializer creates an array and provides initial values for all its components.
and this is irrespective of whether the array is an instance variable or local variable or class variable.
Default values for primitive types : docs
For objects default values is
null
.