[java] Any shortcut to initialize all array elements to zero?

In C/C++ I used to do

int arr[10] = {0};

...to initialize all my array elements to 0.

Is there a similar shortcut in Java?

I want to avoid using the loop, is it possible?

int arr[] = new int[10];
for(int i = 0; i < arr.length; i++) {
    arr[i] = 0;
}

This question is related to java

The answer is


The int values are already zero after initialization, as everyone has mentioned. If you have a situation where you actually do need to set array values to zero and want to optimize that, use System.arraycopy:

static private int[] zeros = new float[64];
...
int[] values = ...
if (zeros.length < values.length) zeros = new int[values.length];
System.arraycopy(zeros, 0, values, 0, values.length);

This uses memcpy under the covers in most or all JRE implementations. Note the use of a static like this is safe even with multiple threads, since the worst case is multiple threads reallocate zeros concurrently, which doesn't hurt anything.

You could also use Arrays.fill as some others have mentioned. Arrays.fill could use memcpy in a smart JVM, but is probably just a Java loop and the bounds checking that entails.

Benchmark your optimizations, of course.


In c/cpp there is no shortcut but to initialize all the arrays with the zero subscript.Ex:

  int arr[10] = {0};

But in java there is a magic tool called Arrays.fill() which will fill all the values in an array with the integer of your choice.Ex:

  import java.util.Arrays;

    public class Main
    {
      public static void main(String[] args)
       {
         int ar[] = {2, 2, 1, 8, 3, 2, 2, 4, 2};
         Arrays.fill(ar, 10);
         System.out.println("Array completely filled" +                          
            " with 10\n" + Arrays.toString(ar));
   }
 }

Yes, int values in an array are initialized to zero. But you are not guaranteed this. Oracle documentation states that this is a bad coding practice.


Initialization is not require in case of zero because default value of int in Java is zero. For values other than zero java.util.Arrays provides a number of options, simplest one is fill method.

int[] arr = new int[5];
Arrays.fill(arr, -1);
System.out.println(Arrays.toString(arr));  //[-1, -1, -1, -1, -1 ]

int [] arr = new int[5];
// fill value 1 from index 0, inclusive, to index 3, exclusive
Arrays.fill(arr, 0, 3, -1 )
System.out.println(Arrays.toString(arr)); // [-1, -1, -1, 0, 0]

We can also use Arrays.setAll() if we want to fill value on condition basis:

int[] array = new int[20];
Arrays.setAll(array, p -> p > 10 ? -1 : p);

int[] arr = new int[5];
Arrays.setAll(arr, i -> i);
System.out.println(Arrays.toString(arr));   // [0, 1, 2, 3, 4]

Yet another approach by using lambda above java 8

 Arrays.stream(new Integer[nodelist.size()]).map(e -> 
 Integer.MAX_VALUE).toArray(Integer[]::new);

You can save the loop, initialization is already made to 0. Even for a local variable.

But please correct the place where you place the brackets, for readability (recognized best-practice):

int[] arr = new int[10];

How it Reduces the Performance of your application....? Read Following.

In Java Language Specification the Default / Initial Value for any Object can be given as Follows.

For type byte, the default value is zero, that is, the value of (byte) is 0.

For type short, the default value is zero, that is, the value of (short) is 0.

For type int, the default value is zero, that is, 0.

For type long, the default value is zero, that is, 0L.

For type float, the default value is positive zero, that is, 0.0f.

For type double, the default value is positive zero, that is, 0.0d.

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

For type boolean, the default value is false.

For all reference types, the default value is null.

By Considering all this you don't need to initialize with zero values for the array elements because by default all array elements are 0 for int array.

Because An array is a container object that holds a fixed number of values of a single type. Now the Type of array for you is int so consider the default value for all array elements will be automatically 0 Because it is holding int type.

Now consider the array for String type so that all array elements has default value is null.

Why don't do that......?

you can assign null value by using loop as you suggest in your Question.

int arr[] = new int[10];
for(int i=0;i<arr.length;i++)
    arr[i] = 0;

But if you do so then it will an useless loss of machine cycle. and if you use in your application where you have many arrays and you do that for each array then it will affect the Application Performance up-to considerable level.

The more use of machine cycle ==> More time to Process the data ==> Output time will be significantly increase. so that your application data processing can be considered as a low level(Slow up-to some Level).


You can create a new empty array with your existing array size, and you can assign back them to your array. This may faster than other. Snipet:

package com.array.zero;
public class ArrayZero {
public static void main(String[] args) {
    // Your array with data
    int[] yourArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    //Creating same sized array with 0
    int[] tempArray = new int[yourArray.length];
    Assigning temp array to replace values by zero [0]
    yourArray = tempArray;

    //testing the array size and value to be zero
    for (int item : yourArray) {
        System.out.println(item);
    }
}
}

Result :

0
0
0
0
0    
0
0
0
0

declare the array as instance variable in the class i.e. out of every method and JVM will give it 0 as default value. You need not to worry anymore


While the other answers are correct (int array values are by default initialized to 0), if you wanted to explicitly do so (say for example if you wanted an array filled with the value 42), you can use the fill() method of the Arrays class:

int [] myarray = new int[num_elts];
Arrays.fill(myarray, 42);

Or if you're a fan of 1-liners, you can use the Collections.nCopies() routine:

Integer[] arr = Collections.nCopies(3, 42).toArray(new Integer[0]);

Would give arr the value:

[42, 42, 42]

(though it's Integer, and not int, if you need the primitive type you could defer to the Apache Commons ArrayUtils.toPrimitive() routine:

int [] primarr = ArrayUtils.toPrimitive(arr);

In java all elements(primitive integer types byte short, int, long) are initialised to 0 by default. You can save the loop.


If you are using Float or Integer then you can assign default value like this ...

Integer[] data = new Integer[20];
Arrays.fill(data,new Integer(0));

    int a=7, b=7 ,c=0,d=0;
    int dizi[][]=new int[a][b];
    for(int i=0;i<a;i++){
        for(int q=d;q<b;q++){
            dizi[i][q]=c;               
            System.out.print(dizi[i][q]);
            c++;
        }

        c-=b+1;
        System.out.println();               
    }

result 0123456 -1012345 -2-101234 -3-2-10123 -4-3-2-1012 -5-4-3-2-101 -6-5-4-3-2-10