Java Initialize an Array with 0 [4 ways]

In this post, I will be sharing how to initialize an Array with 0 in Java. There are 4 ways to achieve our goal:

1. Using default initialization of Array

2. Using the Arrays.fill() method

3. Using declaration and initialization simultaneously

4. Using for loop

Read Also: Find first non-repeated element in integer array in Java

Java Initialize an Array with 0

1. Using default initialization of Array

By using default initialization, we can easily initialize Array with 0.  This line int[] arr = new int[4]; will create an array arr of length 4 with each element has been assigned 0 value.

 public class InitializeArrayZero {
    public static void main(String args[]) {
      int[] arr = new int[4];
      for (int i =0; i < arr.length; i++)
      {
        System.out.print(arr[i] + " ");
      }    
    }
}


Output:
0 0 0 0


2. Using Arrays.fill() method


The Arrays class of java.util package provides a static method fill(). According to Oracle docs, there are many overloaded fill() methods. For our case, it assigns the specified int value i.e. 0 to each element of the specified array of ints as shown below in the example.

 import java.util.Arrays;

public class InitializeArrayZero2 {
    public static void main(String args[]) {
      // Given array    
      int[] arr = new int[]{23, 72, 51, 45};
      Arrays.fill(arr, 0);
      for (int i =0; i < arr.length; i++)
      {
        System.out.print(arr[i] + " ");
      }    
    }
}


Output:
0 0 0 0


3. Using declaration and initialization of Array simultaneously


You can easily initialize an Array with 0 by initializing the array along with the declaration in one line as shown below in the example:

 public class InitializeArrayZero3 {
    public static void main(String args[]) {
      // Given array    
      int[] arr = new int[]{0, 0, 0, 0};
      for (int i =0; i < arr.length; i++)
      {
        System.out.print(arr[i] + " ");
      }    
    }
}


Output:
0 0 0 0


4. Using for loop


Using for loop, you can explicitly initialize the entire array or part of it by zero as shown below in the example:

 public class InitializeArrayZero4 {
    public static void main(String args[]) {
      // Given array    
      int[] arr = new int[]{7, 3, 5, 2};
      for (int i = 0; i < arr.length; i++)
      {
          arr[i] = 0;
      }
      for (int i = 0; i < arr.length; i++)
      {
        System.out.print(arr[i] + " ");
      }    
    }
}


Output:
0 0 0 0


That's all for today. Please mention in the comments if you have any questions related to how to initialize an Array with 0 in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry