How to Initialize an Array with 0 in Java

This article discusses the arrays and different ways to initialize an array with 0 in Java.

Arrays

The arrays are the fundamental data structures, they are sequences of elements stored in contiguous memory locations. The first step when using a data structure involves initializing the data structure which in our case is arrays. Array instantiation or initialization refers to the method of assigning values to array elements of a given data type and size.

We will discuss this in three parts.

  • The first part will deal with initializing a newly created array and how that can be initialized to zero.
  • The second part will be initializing an already existing array to zero.
  • And finally, we will discuss how to initialize user-defined arrays in Java.

Initializing Newly Created Array

When the use case involves an array to be newly created, we have the following methods for initialization at our disposal.

Using Default Initialization of Arrays in Java

Java Language has in-built functionalities to initialize anything which is not explicitly initialized by a programmer. The Java Specifications Document lists various default values for references (null), int, byte, short, long to 0, float to 0.0, etc.

The following code snippet illustrates how array values get initialized according to the data type specified while declaring the array in Java.

Output:

0 0 0 0 0
0.0 0.0 0.0 0.0 0.0

When allocating memory to local variables the Java Virtual Machine or JVM is not required to zero out the underlying memory for them, and thus to avoid random values being allocated to them, the specification mandates initialization to specific values.

These operations help to execute efficient stack operations as and when needed.

Using Initialization After Declaration

You can also explicitly initialize an array to zero just after declaration. Declaration and initialization are two different things.
A declaration does not allocate memory. In order to allocate memory initialization is needed. In Java, you can achieve this separately as well as simultaneously.

The following code illustrates the explicit initialization of arrays with 0 after the declaration in Java

Output:

0 0 0 0 0

In the above example, code first declares the array variable and in the next line it separately and explicitly initialize the array to zero.

Using Simultaneous Initializing and Declaration of Array

As you have seen previously, instead of initialization after declaration, you can also initialize the arrays along with the declaration.
Although this simple change in line of code may look similar but underlying code is completely different for these two methods.

The following code illustrates simultaneous initialization and declaration of arrays in Java.

Output:

0 0 0 0 0

In the above example, code performs simultaneous initialization and declaration of the array variable in a single line.

Notice that in this case there is no need to mention the size anywhere during the declaration and initialization.

Using Reflection in Java

Another workaround for the initialization can be by the use of the Array.newInstance() method in the reflection library of Java.
It creates a new instance of a specified type and dimension given as parameters to the function.

The definition of the function is given below.

Note that you can not pass the negative size of the array, otherwise, the method throws an exception.

The following code will give you a fair idea of how to initialize the array to zero in Java.

Output:

0 0 0 0 0

In the above example code, you can observe that the code calls the newInstance() member function with parameters defining the type and class which is to be returned.

It then assigns the result to the array variable, which by default gets initialized to zero, as you can see in the output.

Initializing Existing Array

In this part, we will learn how to initialize an array to zero if we already have an array declared and initialized with other values already given to us.

Using the Arrays.fill() Function of Java

The Util library of java provides the member function Arrays.fill(). This function can fill the array to any specified data type value either completely throughout the array or partially. It can also be used for multi-dimensional arrays.

The definition of the Arrays.fill() function is given below.

There are multiple overloaded declarations of the method. You can visit here for more information.

In our example we will see the use of the Arrays.fill() function to initialize the array to zero, the following code illustrates this.

Output:

Array Initially:
1 5 6 7 2
Array After using fill():
0 0 0 0 0

Although internally the JVM also applies the for loop in the Arrays.fill() function it is much more efficient than a simple for loop, it does so by lower level implementation internally, making it run faster than a for loop.

Using the for Loop

You can explicitly also initialize the entire array or part of it by zero by using a simple for loop.
This method is often used by new users or learners and it is not as efficient but fairly simple and easy to understand for beginners.

The following code illustrates the usage of for loop for initialization of array to zero in Java.

Output:

Array Initially:
1 5 6 7 2
Array After using for loop:
0 0 0 0 0

You can observe from this code that when the loop runs in each iteration the code assigns the value zero to each individual element sequentially.

Using Reassignment From Another Array

This method involves creating a new array and using it to re assign the originally given array.

This method uses the Java in-built functionality of default initialization and takes it a step further.

The following code illustrates how this reassignment can be performed which in process initializes the original array to zero in Java.

Output:

Array Initially:
1 5 6 7 2
Array After performing reassignment:
0 0 0 0 0

In this example, temp array is created of the same data type and size.

This is a very important requirement for reassignment as only the same data type can be assigned to another variable and the same size is required for arrays.

Using Collections.nCopies() Function of Java

Groups of individual objects in Java are said to be collections in Java. The collection framework in Java has a variety of functions and wrapper classes that you can use for initialization as well.

Integer is a wrapper class whose array can be initialized as shown in the example.

The definition of the Collections.nCopies() method is given below.

The following example illustrates nCopies() method of Collections to initialize Integer array using an existing array.

Output:

Array Initially:
1 5 6 2 8
Array after using nCopies:
0 0 0 0 0

In this example, the code uses an already existing array from which another array of objects is created using the Collections.ncopies() method.

It copies the structure of arrays, but it is initialized to zero. Thus it creates a new Integer class array with the same size as that of the existing array but with initial values of zeroes.

Initializing User-Defined Object Array

In Java, Object arrays can also be user-defined. User defined arrays can also be initialized to zero.

User defined arrays are also declared in the same way as normal primitive data types.

The following example, illustrates how you can initialize the user defined arrays to zero in Java.

Output:

0 0 0 0 0

This example creates a user defined class num with an integer data member value, with a constructor for initialization of each object.

An array of this class arr is then created with a size of five and then all of them are one by one initialized to zero.

Conclusion

These are different ways that can be used to initialize an array to zero in Java. In this article we discussed three different use cases where initialization of arrays can be needed.

In all these three methods we discussed different possible ways of initialization of an array with 0 in java.

That’s all about how to initialize an Array with 0 in Java.

Hope you have learned something new and enjoyed reading the article. Stay tuned for more such articles. Happy learning!

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *