If the individual elements of an int array are not initialized, what is stored in them by default? I apparently found that there is something like an empty array or a null array. What is the difference, and which one applies to my first question?
-
1You can have a zero-length array -- contains no elements. You can have a null array reference -- the reference is null, meaning that no array actually exists. You can have an array with elements that are all set to null -- this is the default for an array of references when it's initially created.Hot Licks– Hot Licks2014-12-15 03:17:55 +00:00Commented Dec 15, 2014 at 3:17
4 Answers
Technically speaking, there's no such thing as a null array; but since arrays are objects, array types are reference types (that is: array variables just hold references to arrays), and this means that an array variable can be null rather than actually pointing to an array:
int[] notAnArray = null;
An empty array is an array of length zero; it has no elements:
int[] emptyArray = new int[0];
(and can never have elements, because an array's length never changes after it's created).
When you create a non-empty array without specifying values for its elements, they default to zero-like values — 0 for an integer array, null for an array of an object type, etc.; so, this:
int[] arrayOfThreeZeroes = new int[3];
is the same as this:
int[] arrayOfThreeZeroes = { 0, 0, 0 };
(though these values can be re-assigned afterward; the array's length cannot change, but its elements can change).
1 Comment
An array has its members initialized to their default values. For int the default is 0. For an Object it's null. A null array is a null Array Reference (since arrays are reference types in Java).
JLS-4.12.5 Initial Values of Variables says in part
For type int, the default value is zero, that is, 0.
and
For all reference types (§4.3), the default value is null.
3 Comments
Integer[], but a double[] would default to 0 (being a primitive type).int[] a = new int[0] has nothing to do with default valuesint[] a = new int[1]; has a default value at index 0. In fact, any array length greater than 0 has a default value at index 0.