What is the default initialization of an array in Java?

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.


Solution 1:

Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.

  • For references (anything that holds an object) that is null.
  • For int/short/byte/long that is a 0.
  • For float/double that is a 0.0
  • For booleans that is a false.
  • For char that is the null character '\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.

Solution 2:

From the Java Language Specification:

  • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):
 - For type byte, the default value is zero, that is, the value of `(byte)0`.
 - For type short, the default value is zero, that is, the value of `(short)0`.
 - For type int, the default value is zero, that is, `0`.
 - For type long, the default value is zero, that is, `0L`.
 - For type float, the default value is positive zero, that is, `0.0f`.
 - For type double, the default value is positive zero, that is, `0.0d`.
 - For type char, the default value is the null character, that is, `'\u0000'`.
 - For type boolean, the default value is `false`.
 - For all reference types (§4.3), the default value is `null`.

Solution 3:

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.

Solution 4:

According to java,

Data Type - Default values

byte - 0

short - 0

int - 0

long - 0L

float - 0.0f

double - 0.0d

char - '\u0000'

String (or any object) - null

boolean - false