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