What Is the Default Initialization of an Array in Java

What is the default initialization of an array in Java?

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.

Do we need to initialize an array in Java?

In Java, all array elements are automatically initialized to the default value. For primitive numerical types, that's 0 or 0.0. For booleans, that's false. For objects, that's null.

In other languages such as C++, the values in an uninitialized array are undefined. Some compilers may initialize to 0/null similarly for security, and it's very bad practice to rely on this. However, this behavior is well defined in Java and so it's perfectly okay to create a primitive array and trust that the values are 0.

Initializing an object in an array with a default value - java

The Java 8 way:

MyObject[] arr = Stream.generate(() -> new MyObject())
.limit(5)
.toArray(MyObject[]::new);

This will create an infinite Stream of objects produced by the supplier () -> new MyObject(), limit the stream to the total desired length, and collect it into an array.

If you wanted to set some properties on the object or something, you could have a more involved supplier:

() -> {
MyObject result = new MyObject();
result.setName("foo");
return result;
}

Any shortcut to initialize all array elements to zero?

A default value of 0 for arrays of integral types is guaranteed by the language spec:

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10) [...] For type int, the default value is zero, that is, 0.  

If you want to initialize an one-dimensional array to a different value, you can use java.util.Arrays.fill() (which will of course use a loop internally).

What are the default values of the char array in Java?

It's the same as for any type: the default value for that type. (So the same as you'd get in a field which isn't specifically initialized.)

The default values are specified in JLS 4.12.5:

For type char, the default value is the null character, that is, '\u0000'.

Having said that, it sounds like really you want a List<Character>, which can keep track of the actual size of the collection. If you need random access to the list (for example, you want to be able to populate element 25 even if you haven't populated element 2) then you could consider:

  • A Character[] using null as the "not set" value instead of '\u0000' (which is, after all, still a character...)
  • A Map<Integer, Character>
  • Sticking with char[] if you know you'll never, ever, ever want to consider an element with value '\u0000' as "set"

(It's hard to know which of these is the most appropriate without knowing more about what you're doing.)

int array initialization

First thing to understand is that, local varibles are stored on stack which are not initialized explicitly with their default values. While instance variables are stored on Heap, and they are by default initialized with their default value.

Also, objects are also created on Heap, regardless of whether an instance reference variable is holding its reference, or a local reference variable.


Now, what happens is, when you declare your array reference like this as local variable, and initialize it with an array: -

int[] in = new int[5];

The array reference (in) is stored on stack, and a memory is allocated for array capable of holding 5 integer elements on heap (Remember, objects are created on Heap). Then, 5 contiguous memory location (size = 5), for storing integer value are allocated on Heap. And each index on array object holds a reference to those memory location in sequence. Then the array reference points to that array. So, since memory for 5 integer values are allocated on Heap, they are initialized to their default value.

And also, when you declare your array reference, and don't initialize it with any array object: -

int[] in;

The array reference is created on Stack (as it is a local variable), but it does not gets initialized to an array by default, and neither to null, as is the case with instance variables.


So, this is how allocation looks like when you use the first way of array declaration and initialization: -

"Your array reference"
"on stack"

| | "Array object on Heap"
+----+
| in |----------> ([0, 0, 0, 0, 0])
+----+
"Stack" "Heap"

Java: Initialize an array of 0.0 or 1 or A with size n*1 or size n*m

To make it into a one-liner, you can make a simple method, that does it.
You can pass the size and value and return the new ArrayList:

static ArrayList<String> populateArrayList(int size, String defaultValue) {
ArrayList<String> list = new ArrayList<String>();
for (int i=0; i<size; i++)
list.add(defaultValue);
return list;
}

If you wish to use static list - array, then similar code can be applied:

static String[] populateArray(int size, String defaultValue) {
String[] array = new String[size];
for (int i=0; i<size; i++)
array[i] = defaultValue;
return array;
}

And then to use, just call the method and assign its returned value to a new list:

ArrayList<String> data1 = populateArrayList(100, "Doggo");
String[] data2 = populateArray(100, "Moo-moo");

Default values

As stated in comments, variables of different data types have their default values that are used in arrays, object params etc.

  • for numerics it is 0,
  • for boolean - true,
  • for String and other type it is null

More about default values here



Related Topics



Leave a reply



Submit