Any shortcut to initialize all array elements to zero?

Java

Java Problem Overview


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;
}

Java Solutions


Solution 1 - Java

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).

Solution 2 - Java

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);

Solution 3 - Java

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

Solution 4 - Java

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).

Solution 5 - Java

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];

Solution 6 - Java

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));

Solution 7 - Java

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

Solution 8 - Java

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.

Solution 9 - Java

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));
   }
 }

Solution 10 - Java

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]

Solution 11 - Java

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

Solution 12 - Java

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.

Solution 13 - Java

Yet another approach by using lambda above java 8

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

Solution 14 - Java

You defined it correctly in your question, it is nearly the same as for C++. All you need to do for the primitive data type is to initialize the array. Default values are for int 0.

int[] intArray = new int[10];

Solution 15 - Java

you can simply do the following

 int[] arrayOfZeros= new int[SizeVar];

Solution 16 - Java

	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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongameoverView Question on Stackoverflow
Solution 1 - JavaMichael BorgwardtView Answer on Stackoverflow
Solution 2 - JavaAdam ParkinView Answer on Stackoverflow
Solution 3 - JavaArne DeutschView Answer on Stackoverflow
Solution 4 - JavaJugal ThakkarView Answer on Stackoverflow
Solution 5 - JavaKLEView Answer on Stackoverflow
Solution 6 - JavaPankaj GoyalView Answer on Stackoverflow
Solution 7 - JavaKavishankar KarunakaranView Answer on Stackoverflow
Solution 8 - JavaNateSView Answer on Stackoverflow
Solution 9 - JavaAnsh SrivastavaView Answer on Stackoverflow
Solution 10 - JavadaemonThreadView Answer on Stackoverflow
Solution 11 - JavaDhruvam GuptaView Answer on Stackoverflow
Solution 12 - JavanateView Answer on Stackoverflow
Solution 13 - Javabrahmananda KarView Answer on Stackoverflow
Solution 14 - JavaAndrej BudayView Answer on Stackoverflow
Solution 15 - JavaIkbelView Answer on Stackoverflow
Solution 16 - JavaUbeydView Answer on Stackoverflow