Monday, May 7, 2012

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;


Source: Tips4all

3 comments:

  1. 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 array to a different value, you can use java.util.Arrays.fill() (which will of course use a loop internally).

    ReplyDelete
  2. In java all elements are initialised to 0 by default. You can save the loop.

    ReplyDelete
  3. 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];

    ReplyDelete