Hristo Hristo - 1 year ago 92
Java Question

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];

will print to standard out. Also, if I do this:

static final int UN = 0;
int[] arr = new int[5];

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
which would mean I don't have to loop through the array and initialize it?


Answer Source

Everything in Java not explicitly set to something, 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download